list = ["word1", "word2", "word3"]
print list.index("word1")
这很好用!
但我如何获得这个索引:
list = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
print list.index("word4")
好吧,那不起作用,错误:
ValueError: "word4" is not in list
我期待一个像1,0
list = ["word1", "word2", "word3"]
print list.index("word1")
这很好用!
但我如何获得这个索引:
list = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
print list.index("word4")
好吧,那不起作用,错误:
ValueError: "word4" is not in list
我期待一个像1,0
尝试这样的事情:
def deep_index(lst, w):
return [(i, sub.index(w)) for (i, sub) in enumerate(lst) if w in sub]
my_list = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
print deep_index(my_list, "word4")
>>> [(1, 0)]
这将返回一个元组列表,其中第一个元素指向外部列表中的索引,第二个元素指向该子列表中单词的索引。
对于多维索引,假设您的数据可以表示为 NxM(而不是一般的列表列表),numpy 非常有用(而且速度很快)。
import numpy as np
list = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
arr = np.array(list)
(arr == "word4").nonzero()
# output: (array([1]), array([0]))
zip(*((arr == "word4").nonzero()))
# output: [(1, 0)] -- this gives you a list of all the indexes which hold "word4"
我认为您必须手动找到它-
def index_in_list_of_lists(list_of_lists, value):
for i, lst in enumerate(list_of_lists):
if value in lst:
break
else:
raise ValueError, "%s not in list_of_lists" %value
return (i, lst.index(value))
list_of_lists = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
print index_in_list_of_lists(list_of_lists, 'word4') #(1, 0)
def get_index(my_list, value):
for i, element in enumerate(my_list):
if value in element:
return (i, element.index(value))
return None
my_list= [["word1", "word2", "word3"], ["word4", "word5", "word6"]]
print get_index(my_list, "word4")
打印 (1, 0)
将来,尽量避免命名你的变量list
,因为它会覆盖 Python 的内置list
.
lst = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
def find_index_of(lst, value):
for index, word in enumerate(lst):
try:
inner_index = word.index(value)
return (index, inner_index)
except ValueError:
pass
return ()
这循环遍历 的每个元素,lst
它将:
index
. value
如果我们找到了元素,那么让我们返回索引。ValueError
(因为该元素不在列表中),那么让我们继续下一个列表。输出:
find_index_of(lst, 'word4') # (1, 0)
find_index_of(lst, 'word6') # (1, 2)
find_index_of(lst, 'word2') # (0, 1)
find_index_of(lst, 'word78') # ()