Python 如何获取列表中列表的索引?
这个很好用 但我如何获取此项的索引:Python 如何获取列表中列表的索引?,python,Python,这个很好用 但我如何获取此项的索引: list = ["word1", "word2", "word3"] print list.index("word1") 那不行,错误: list = [["word1", "word2", "word3"],["word4", "word5", "word6"]] print list.index("word4") 我希望得到像1,0这样的答案,我想你必须手动找到它- ValueError: "word4" is not in list 试着这样做:
list = ["word1", "word2", "word3"]
print list.index("word1")
那不行,错误:
list = [["word1", "word2", "word3"],["word4", "word5", "word6"]]
print list.index("word4")
我希望得到像
1,0
这样的答案,我想你必须手动找到它-
ValueError: "word4" is not in list
试着这样做:
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 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)]
打印(1,0)以后,尽量避免命名变量
list
,因为它将覆盖Python内置的list
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")
这将循环通过lst
的每个元素,它将:
- 尝试获取
值的
。如果我们已经找到了元素,那么让我们返回索引索引
- 但是,如果Python抛出一个
(因为元素不在列表中),那么让我们继续下一个列表李>ValueError
- 如果未找到任何内容,则返回空元组
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 ()
对于多维索引,假设您的数据可以表示为NxM(而不是列表的一般列表),numpy非常有用(而且非常快速)
OP需要两个数字,一个用于索引外部列表,一个用于索引内部列表。要匹配
(行,列)
惯例,您应该切换(i,sub.index(w))
@askewchan哇,谢谢!在代码中它实际上是正确的,我只是在输出中输入错误。哈,我在写的时候非常困惑,因为它看起来是正确的。。。但是不匹配。
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') # ()
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"