views:

33

answers:

3

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),     <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!

====================

+1  A: 

1.

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

2.

results = [ foo() for _ in xrange(100) ]
eumiro
A: 

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]
>>> 
pyfunc
I recalled there is an iter version of the result collection, can you also mark it here?
user478514
@user478514: I have provided the example.
pyfunc
thanks, just want to know a little more, why (x for x in range(10)) return a generator? how it can be coded, I means how python know the () should return a generator not a tuple?
user478514
@user478514: Rather than repeat the answer here :) Read the SO at http://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehension
pyfunc
+1  A: 

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)]
Swiss