如何在列表中获取列表的索引?

5
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的答案。
5个回答

5

可以尝试以下方式:

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)]

这将返回一个元组列表,其中第一个元素指向外部列表中的索引,第二个元素指向该子列表中单词的索引。

为了匹配(行,列)约定,您应该交换(i,sub.index(w))的顺序。 - askewchan
@askewchan 哎呀,谢谢提醒!实际上代码是正确的,只是我在输出时打错了。 - tobias_k
1
哈哈,我在写那段代码的时候非常困惑,因为它看起来很对...但实际上并不匹配。 - askewchan

2

对于多维索引,假设您的数据可以表示为 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"

1

我认为你必须手动找到它 -

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)

1
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)


OP想要两个数字,一个用于索引外部列表,另一个用于索引内部列表。 - Robᵩ

1
在未来,请避免将变量命名为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的每个元素,并且会:
  • 尝试获取valueindex。如果找到了该元素,则返回索引。
  • 但是,如果Python引发了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') # ()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接