开发者

how to use python list comprehensions replace the function invoke inside of "for" stmt?

Sorry, I just found the

id = [conn.cursor() for x in range(100) ]

also works, so my concern will not be a problem anymore. Thanks for all of your answer, all of you are really fast.


All,

id = [(conn.cursor(),x) for x in range(100) ]
>>> id
[(<sqlite3.Cursor object at 0x01D14DA0>, 0), (<sqlite3.Cursor object at 0x01D14DD0>, 1), (<sqlite3.Cursor object at 0x01D14E00>, 2), (<sqlite3.Cursor object at 0x01D14E30>, 3), (<sqlite3.Cursor object at 0x01D14EC0>, 4), (<sqlite3.Cursor object at 0x01D14EF0>, 5),    开发者_如何学Go <omitted>

but I do not need the id[1] col actually, and I do not want use the

for x in range(100):
    id.append(conn.cursor())

for some reason, do you think I can use the list comprehension to get what I want? Also similiar question, if I want to invoke one function 100 times.

def foo():
    pass

for x in range(100):
    foo()

Can that "for" be rewrite to a list comprehensions style either?

Thanks!


For the second question

List comprehensions are used for generating another list as output of iteration over other list or lists. Since you want to run foo a numer of times, it is more elegant and less confusing to use for .. in range(..) loop.

If you are interested in collating the return value of foo, then you should use list comprehension else for loop is good. At least I would write it that way.

See the example below:

>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def foo(): print 'foo'
... 
>>> 
>>> [foo() for x in range(10)]
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
[None, None, None, None, None, None, None, None, None, None]
>>> 

[Edit: As per request]

The iter version that was provided by eumiro.

>>> results = ( foo() for _ in xrange(10) )
>>> results
<generator object <genexpr> at 0x10041f960>
>>> list(results)
foo
foo
foo
foo
foo
foo
foo
foo
foo
foo
[None, None, None, None, None, None, None, None, None, None]
>>> 


You don't have to use the variable you are iterating over in your list iteration. This will work just fine:

id = [conn.cursor() for _ in range(100)]


1.

cursors = [ conn.cursor() for _ in xrange(100) ]

2.

results = [ foo() for _ in xrange(100) ]
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜