在python中查找嵌套列表中元素的索引

新手上路,请多包涵

我正在尝试获取 python 嵌套列表中元素的索引 - 例如 [[a, b, c], [d, e, f], [g,h]] (并非所有列表的大小都相同)。我试过使用

strand_value= [x[0] for x in np.where(min_value_of_non_empty_strands=="a")]

但这只返回一个空列表,即使该元素存在。知道我做错了什么吗?

原文由 biophys_chem 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 982
2 个回答
def find_in_list_of_list(mylist, char):
    for sub_list in mylist:
        if char in sub_list:
            return (mylist.index(sub_list), sub_list.index(char))
    raise ValueError("'{char}' is not in list".format(char = char))

example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

find_in_list_of_list(example_list, 'b')
(0, 1)

原文由 DainDwarf 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 List comprehension 和 enumerate 来做到这一点

代码:

 lst=[["a", "b", "c"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]

输出:

 ['0 0']

脚步:

  • 我已经枚举了列表列表并得到了它的索引和列表
  • 然后我枚举了得到的列表并检查它是否与 check 变量匹配,如果匹配则将其写入列表

这给出了所有可能的输出

IE)

代码2:

 lst=[["a", "b", "c","a"], ["d", "e", "f"], ["g","h"]]
check="a"
print ["{} {}".format(index1,index2) for index1,value1 in enumerate(lst) for index2,value2 in enumerate(value1) if value2==check]

给出:

 ['0 0', '0 3']

笔记:

  • 如果你愿意,你可以很容易地将它变成列表列表而不是字符串

原文由 The6thSense 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题