简体   繁体   English

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

[英]Finding the index of an element in nested lists in python

I am trying to get the index of an element in nested lists in python - for example [[a, b, c], [d, e, f], [g,h]] (not all lists are the same size). 我正在尝试获取python嵌套列表中元素的索引-例如[[a, b, c], [d, e, f], [g,h]] (并非所有列表的大小相同) 。 I have tried using 我尝试使用

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

but this is only returning an empty list, even though the element is present. 但这仅返回一个空列表,即使该元素存在。 Any idea what I'm doing wrong? 知道我在做什么错吗?

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)

suppose your list is like this: 假设您的清单是这样的:

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 gives the list number and pos gives the position in that list list_no给出列表号, pos给出列表中的位置

You could do this using List comprehension and enumerate 您可以使用列表理解并枚举

Code: 码:

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]

Output: 输出:

['0 0']

Steps: 脚步:

  • I have enumerated through the List of List and got it's index and list 我已经通过列表列表进行枚举,并得到了它的索引和列表
  • Then I have enumerated over the gotten list and checked if it matches the check variable and written it to list if so 然后我枚举了获得的列表,并检查它是否与check变量匹配,如果符合,则将其写入列表

This gives all possible output 这给出了所有可能的输出

ie)

Code2: 代码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]

Gives: 给出:

['0 0', '0 3']

Notes: 笔记:

  • You can easily turn this into list of list instead of string if you want 您可以根据需要轻松地将其转换为列表列表,而不是字符串

does this suffice? 这足够吗?

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

This will return 0 - 0. First zero is the index of the subarray inside array, and the last zero is the 'a' index inside subarray. 这将返回0-0。第一个零是数组内子数组的索引,最后一个零是子数组内的'a'索引。

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

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