kivava

Python - get position in list - Stack Overflow

Hmmm. There was an answer with a list comprehension here, but it’s disappeared.

Here:

 [i for i,x in enumerate(testlist) if x == 1]

Example:

>>> testlist[1, 2, 3, 5, 3, 1, 2, 1, 6]>>> [i for i,x in enumerate(testlist) if x == 1][0, 5, 7]

Update:

Okay, you want a generator expression, we’ll have a generator expression. Here’s the list comprehension again, in a for loop:

>>> for i in [i for i,x in enumerate(testlist) if x == 1]:...     print i... 057

Now we’ll construct a generator…

>>> (i for i,x in enumerate(testlist) if x == 1)<generator object at 0x6b508>>>> for i in (i for i,x in enumerate(testlist) if x == 1):...     print i... 057

and niftily enough, we can assign that to a variable, and use it from there…

>>> gen = (i for i,x in enumerate(testlist) if x == 1)>>> for i in gen: print i... 057

And to think I used to write FORTRAN.

Posted via email from 思發隨醒 | Comment »