简体   繁体   中英

How to get list of indexes of all occurences of the same value in list of lists?

Having a list of lists,

mylist = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3]]

I need a method to get list containing indexes of all elements of some certain value, '3' for example. So for value of '3' such list of indexes should be

[[0, 1], [1, 0], [2, 3]]

Thanks in advance.

Update : we can have several instances of sought-for value ('3' in our case) in same sublist, like

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3, 3]]

So desired output will be [[0, 1], [1, 0], [2, 3], [2, 4]] .

I suppose that my solution is slightly naive, here it is:

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3, 3]]
value = 3
list_of_indexes = []

for i in range(len(my_list)):
        for j in range(len(my_list[i])):
            if my_list[i][j] == value:
                index = i, j
                list_of_indexes.append(index)

print list_of_indexes

>>[(0, 1), (1, 0), (2, 3), (2, 4)]]

It will be great to see more compact solution

Assuming the value appears once in each sublist, you could use the following function, which makes use of the built in enumerate function and a list comprehension:

my_list = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3]]

def func(my_list, x):
    return [[idx, sublist.index(x)] for idx, sublist in enumerate(my_list)]

answer = func(my_list, 3)
print(answer)

Output

[[0, 1], [1, 0], [2, 3]]

Easy way,

def get_val(mylist, val):
    for ix, item in enumerate(mylist):
        yield [ix, item.index(val)]

mylist = [[1, 3, 4], [3, 6, 7], [8, 0, -1, 3]]

val = list(get_val(mylist, 3))
print(val)

Output:

[[0, 1], [1, 0], [2, 3]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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