Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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
获取列表中元素的索引(python)_Python_List_Indexing - Fatal编程技术网

获取列表中元素的索引(python)

获取列表中元素的索引(python),python,list,indexing,Python,List,Indexing,我不明白为什么在下一个示例中获取列表中元素的索引会有所不同: list = [1, 1, 1, 4] print list.index(list[3]) 将预期的3作为列表中的第四个索引元素返回 但是 意外返回0 有什么区别?它是Python3.3的列表。索引(x)总是返回第一个匹配的索引。在第一种情况下,第一个匹配位于索引3,即4位于索引3,而在第二种情况下,第一个匹配位于索引0,即1位于索引0。1也位于指数1、2和3处。来自: 列表.索引(x) 返回值为x的第一项列表中的索引。如果没有

我不明白为什么在下一个示例中获取列表中元素的索引会有所不同:

list = [1, 1, 1, 4]

print list.index(list[3]) 
将预期的3作为列表中的第四个索引元素返回

但是

意外返回0

有什么区别?它是Python3.3的列表。索引(x)总是返回第一个匹配的索引。在第一种情况下,第一个匹配位于索引3,即4位于索引3,而在第二种情况下,第一个匹配位于索引0,即1位于索引0。1也位于指数1、2和3处。

来自:

列表.索引(x)

返回值为x的第一项列表中的索引。如果没有此类项目,则为错误


您正在返回第一个匹配项的索引。

1st使用list作为变量名是不好的做法:

index search the element from the start of list, so in here you will get always 0:
>>> my_list = [1, 1, 1, 1]  
>>> my_list.index(1)
0
>>> my_list.index(my_list[3])
0
索引(n)将返回“列表”中第一个“n”的索引。 在你的例子中

list = [1, 1, 1, 1] #list[3] will equal 1
因此
list.index([3])
list.index(1)
将返回0,或列表中第一个1的索引

list = [1, 1, 1, 1] #list[3] will equal 1