开发者

Python std.stdout.write loop problems

I'm not sure of what's going on here, but I have some python code:

import sys

max_cols = 350
max_rows = 1
r1 = range(max_rows)
r2 = range(max_cols)

for y in r1:
    for x in r2:
        sys.stdout.write('something')
        if x is not max_cols-1:
            sys.stdout.write(',')

Now, this works fine for values of max_cols <= 257. However, if you use >= 258, you end up with an extra ',' at the end. (The idea here is obviously to generate a CSV file.)

Now, 256 is a CS number, so there's clearly something going on here that I'm unaware of, since everything works perfectly up until that point. This also happens when I try to w开发者_运维知识库rite to a file using the same pattern.

Why does this happen?

Using Python 3.2.


is is not for checking equality but for checking identity. x is y is only true if both variables refer to the same object. As it happens, CPython resuses objects for small integers - but in general, the concept of identity is very different from the concept of equality. Use the correct operators, == and != for equality and inequality respectively, and it works.

Also note that the code can be made much simpler and robust by just using the csv module. No need to reinvent the wheel.


The CPython implementation caches small numbers, so all instances of the number 12 are the same object. The is operator compares the identities of objects, not their values. What you wanted to do was use the != operator to compare the values.

It's likely that your instance of the CPython implementation caches numbers up to 256.

Incidentally, whenever you bump into a pattern like this, where you have to drop the last separator from a list of delimited things, str.join is probably what you wanted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜