我正试图得到这样一个列表中元素的索引号
scores = [100,22,33,44,22,56]
我想得到22的两个索引号。 我试图通过将索引号存储到列表中来实现这一点。 但当我在这个例子中找到两个索引号后,程序突然 结束,因为它在第二个22之后找不到任何22,因此没有给我机会打印我找到的索引号。 你如何使它打印出来的索引号码没有任何错误?你知道吗
scores = [100,22,11,22,44,66,77]
position = 0
counter = []
findthis = 22
for x in scores:
position = scores.index(findthis, position)
counter.append(position)
position = position + 1
print(counter)
像这样使用
try
和except
块:但是我同意纪尧姆·杜普雷的观点,用一个更简单的方法来代替。你知道吗
如果要在分数列表中使用enumerate,请使用
findthis
的所有索引:i
是分数中每个元素的索引,ele
是每个实际元素。你知道吗一旦您通过了列表中第二个
22
的索引,您就会得到错误,因为列表中没有22
,您的代码运行了两次迭代,然后就剩下了-> 44,66,77]
。你知道吗您应该考虑这种更简单的方法:
相关问题 更多 >
编程相关推荐