Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中查找列表索引号?_Python_Python 3.x - Fatal编程技术网

在Python3中查找列表索引号?

在Python3中查找列表索引号?,python,python-3.x,Python,Python 3.x,我在Python中处理大量素数列表,并试图通过在其他地方引用来查找列表中素数的位置号(如本例中y的2->[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的列表中的位置,但收到错误消息: Traceback (most r

我在Python中处理大量素数列表,并试图通过在其他地方引用来查找列表中素数的位置号(如本例中y的2->
[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的列表中的位置,但收到错误消息:

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print([primelist].index(104395303))
ValueError: 104395303 is not in list
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
打印([primelist]。索引(104395303))
ValueError:104395303不在列表中
我的故障排除尝试的证据截图

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

primelist.index(104395303)

这已经是一个列表了。不要将它包装在另一个列表中。

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

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

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

primelist = [104395303, 104395337]
num=104395303
index_= primelist.index(num) if num in primelist else -1 #index_ would be 0
如果元素不在列表中,if-else将非常有用,例如
num=104395303
if-if-we
primelist.index(num)
它将抛出
ValueError
,因为我们试图查找的元素不存在,但是如果未找到元素,我们可以使用
if-else
块将索引指定为
-1

primelist = [104395303, 104395337]
num=104395304 # num not present in list
index_= primelist.index(num) if num in primelist else -1 #index_ would be -1
或者将代码包装在
中,尝试除块

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

print(index_)
。。。我应该做这项工作

index函数只查找传递的元素的索引。您所做的是将列表放入另一个列表中。现在,如果要检查索引,则必须使用:

[primelist][0].index(104395337)
另一个更简单的方法是:

104395303 in primelist
True

因为这很容易与if条件结合,而且非常方便。

仅删除[]。print(primelist.index(104395303))如果在列表中找不到元素,它将抛出一个错误
104395303 in primelist
True