在Python3中查找列表索引号?

2024-04-20 05:11:49 发布

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

我在Python中使用大量的素数列表,并试图通过在其他地方引用来查找列表中质数的位置号(在本例中是y的位置号-gt;[x,x,y,x]):

primelist = [104395303, 104395337] #it's a lot longer than that but you get the idea
print([primelist].index(104395303))

我希望它返回0-即104395303在名为primelist的列表中的位置,但是得到了错误消息:

^{pr2}$

在我的故障排除尝试的证据截图。在

here

为什么我收到这个错误?除了我已经尝试过的以外,我应该做些什么来达到我想要的目标?在


Tags: gtyou列表that地方错误it素数
3条回答

您可以在运行.index之前检查它是否存在

primelist = [104395303, 104395337]
index_check = 104395303 in primelist
if(index_check):
    print(primelist.index(104395303))
else:
    print("Number not found")

如果存在,则使用python if else块获取索引;如果不存在,则使用-1

primelist = [104395303, 104395337]
num=104395303
index_= primelist.index(num) if num in primelist else -1 #index_ would be 0

如果else对于元素不在列表中的情况是有用的,例如num=104395303如果我们这样做primelist.index(num),它将抛出ValueError,因为我们要查找的元素不存在,但是使用if else块,如果找不到元素,我们可以将索引指定为-1。在

^{pr2}$

{cd8>用你的代码换行

primelist = [104395303, 104395337]
num=104395304
try:
    index_= primelist.index(num)
except ValueError:
    index_=-1

print(index_)
primelist.index(104395303)

已经是一张单子了。别把它放在另一张单子里。在

相关问题 更多 >