我不能不中断程序就打印出我的索引号

2024-09-28 21:51:00 发布

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

我正试图得到这样一个列表中元素的索引号

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)

Tags: in程序元素列表forindex错误counter
3条回答

像这样使用tryexcept块:

scores = [100,22,11,22,44,66,77]
position = 0
counter = []
findthis = 22

while True:
    try:
         position = scores.index(findthis, position)
         counter.append(position)
         position = position + 1
    except ValueError:
         break

print(counter)

但是我同意纪尧姆·杜普雷的观点,用一个更简单的方法来代替。你知道吗

如果要在分数列表中使用enumerate,请使用findthis的所有索引:

print([i for i, ele in enumerate(scores) if ele == findthis])

i是分数中每个元素的索引,ele是每个实际元素。你知道吗

一旦您通过了列表中第二个22的索引,您就会得到错误,因为列表中没有22,您的代码运行了两次迭代,然后就剩下了-> 44,66,77]。你知道吗

scores[position:]
1st iteration -> [22, 11, 22, 44, 66, 77]
2nd           ->  [22, 44, 66, 77]
3rd           ->  [44, 66, 77] # error

您应该考虑这种更简单的方法:

scores = [100,22,11,22,44,66,77]
position = 0
counter = []
findthis = 22

for x in scores:
     if x==findthis:
          counter.append(position)
     position = position + 1 

相关问题 更多 >