繁体   English   中英

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

[英]Finding the index of an element in nested lists in 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")]

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

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)

假设您的清单是这样的:

lst = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g','h']]
list_no = 0
pos = 0
for x in range(0,len(lst)):
    try:
        pos = lst[x].index('e')
        break
    except:
        pass

list_no = x

list_no给出列表号, pos给出列表中的位置

您可以使用列表理解并枚举

码:

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变量匹配,如果符合,则将其写入列表

这给出了所有可能的输出

代码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']

笔记:

  • 您可以根据需要轻松地将其转换为列表列表,而不是字符串

这足够吗?

array = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for subarray in array:
    if 'a' in subarray:
        print(array.index(subarray), '-', subarray.index('a'))

这将返回0-0。第一个零是数组内子数组的索引,最后一个零是子数组内的'a'索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM