如何获取项目在列表中的位置? [英] How to get item's position in a list?

查看:88
本文介绍了如何获取项目在列表中的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历列表,如果满足特定条件,我想打印出该项目的索引.我该怎么办?

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?

示例:

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

推荐答案

嗯.这里有一个列表理解的答案,但它消失了.

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

这里:

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

示例:

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

更新:

好的,您需要一个生成器表达式,我们将有一个生成器表达式.再次在for循环中,这是列表理解:

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

现在我们将构造一个生成器...

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

非常有趣的是,我们可以将其分配给变量,然后从那里使用它...

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

想想我曾经写过FORTRAN.

And to think I used to write FORTRAN.

这篇关于如何获取项目在列表中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆