对具有重复元素的列表使用.index()

2024-03-28 20:12:37 发布

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

所以我检查了一个列表并打印了所有等于3的值

for item in top:
    if item == 3:
        print('recommendation found at:')
        print(top.index(item))

问题是这将继续打印值为3的第一个元素。如何打印每个元素的位置值为3?在


Tags: in元素列表forindexiftopitem
2条回答

使用^{}。在

>>> top = [1, 3, 7, 8, 3, -3, 3, 0]
>>> hits = (i for i,value in enumerate(top) if value == 3)

这是一个生成器,它将生成所有索引i,其中top[i] == 3。在

^{pr2}$

https://docs.python.org/2/tutorial/datastructures.html
Index:“返回值为x的第一项的列表中的索引。”

一个简单的解决方案是:

for i in range(len(top)):
    if top[i] == 3:
        print('recommendation found at: ' + str(i))

相关问题 更多 >