Finding the index of an element in nested lists in python

牧云@^-^@ 提交于 2019-12-08 06:22:10

问题


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). 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?


回答1:


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)



回答2:


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




回答3:


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

This gives all possible output

i.e.)

Code2:

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



回答4:


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.



来源:https://stackoverflow.com/questions/33938488/finding-the-index-of-an-element-in-nested-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!