如何在列表中獲取項目的位置? - How to get item's position in a list? -开发者知识库

如何在列表中獲取項目的位置? - How to get item's position in a list? -开发者知识库,第1张

I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?

我正在迭代一個列表,如果它滿足某個條件,我想打印出這個項目的索引。我該怎么做呢?

Example:

例子:

testlist = [1,2,3,5,3,1,2,1,6]for item in testlist:    if item == 1:        print position

10 个解决方案

#1


231  

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循環中:

>>> 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.

我曾經寫過FORTRAN。

最佳答案:

本文经用户投稿或网站收集转载,如有侵权请联系本站。

发表评论

0条回复