Python中的数组索引 [英] Array Indexing in Python
问题描述
在这里开始学习python的人在想什么.
Beginner here, learning python, was wondering something.
这给了我第二个要素:
list = [1,2,3,4]
list.index(2)
2
但是当我尝试这样做时:
But when i tried this:
list = [0] * 5
list[2] = [1,2,3,4]
list.index[4]
我得到一个错误.有什么方法可以从数组中拉出元素的索引,而不管它放在什么列表中?我知道字典是可能的:
I get an error. Is there some way to pull the index of an element from an array, no matter what list it's placed into? I know it's possible with dictionaries:
info = {first:1,second:2,third:3}
for i in info.values:
print i
1
2
3
列表有类似的东西吗?
推荐答案
index
方法无法达到您的期望.要获得索引项,必须使用 []
语法:
The index
method does not do what you expect. To get an item at an index, you must use the []
syntax:
>>> my_list = ['foo', 'bar', 'baz']
>>> my_list[1] # indices are zero-based
'bar'
index
用于从项目中获取索引:
index
is used to get an index from an item:
>>> my_list.index('baz')
2
如果您要问是否有任何方法可以使 index
递归到子列表中,答案是否定的,因为它必须返回某些内容,然后您可以将其传递给[]
和 []
从不进入子列表.
If you're asking whether there's any way to get index
to recurse into sub-lists, the answer is no, because it would have to return something that you could then pass into []
, and []
never goes into sub-lists.
这篇关于Python中的数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!