如何在列表中获取项目的位置?

2024-03-29 01:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在遍历一个列表,如果满足某个条件,我想打印出该项的索引。我该怎么做?

示例:

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

Tags: in示例列表forifpositionitem条件
3条回答

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

这里:

 [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循环中:

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

现在我们要建造一个发电机。。。

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

非常漂亮的是,我们可以把它赋给一个变量,然后在那里使用它。。。

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

想想我以前写FORTRAN。

下面呢?

print testlist.index(element)

如果不确定要查找的元素是否在列表中,可以添加一个初步检查,如

if element in testlist:
    print testlist.index(element)

或者

print(testlist.index(element) if element in testlist else None)

或者“pythonic方式”,我不太喜欢这种方式,因为代码不太清晰,但有时效率更高

try:
    print testlist.index(element)
except ValueError:
    pass

使用枚举:

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

相关问题 更多 >