python 2.7 for loop to generate a list

I have tested in Python 2.7, the two styles are the same. My confusion is, when reading first method to generate a list, I am always a bit confused if i%2 == 0 controls if we should execute the whole loop of i in range(100) , or i%2 == 0 is under loop of i in range(100) . I have the confusion maybe in the past I write Java and C++, thinking methods from there.

Looking for advice how to read list generation code, normally the pattern is [<something before loop> <the loop> <something after the loop>] , in this case "something before loop" is 1 , and "the loop" is for i in range(100) and "something after the loop" is i%2 == 0 .

Also asking for advice if writing code in method 1 is good coding style in Python 2.7? Thanks.

a = [1 for i in range(100) if i%2 == 0]

print a

a=[]
for i in range(100):
    if i%2==0:
        a.append(1)

print a

Edit 1 ,

I also want to compare of using xrange in an explicit loop (compare to first method of list comprehension for pros and cons), for example,

a=[]
for i in xrange(100):
    if i%2==0:
        a.append(1)

print a

Edit 2 ,

a = [1 for i in xrange(100) if i%2 == 0]

1) as already mentioned in python 2.7 it is usually suggested to use xrange since it will (like in C) only keep a counter that will be incremented. Instead the range is really creating in memory a whole list from 0 till 99! Maybe here you have to think, if you need the 100 included --> then please use 101 ;)

2) You got my point, the question is valid and you have to think that operation will be executed indeed "under" the loop!!

Bearing in mind that the list comprehension is quite powerful in order to create the needful!! Anyway be careful that in some cases is not so easy to read especially when you are using inside multiple variable like x,y and so on.

I would chose your first line, just take care of min and max of your array. As said maybe you have to incorporate the 100th element and you can speed up using the xrange function instead of range. a = [1 for i in range(100) if i%2 == 0]

3) A good suggestion is also to document yourself on xrange and while loop --> on stackoverflow you can find plenty of discussions looking for the speed of the two mentioned operation!! (This is only suggestion)

Hope this clarify your query! Have a nice day!

链接地址: http://www.djcxy.com/p/69960.html

上一篇: 用于循环生成字典的Python

下一篇: python 2.7 for循环来生成一个列表