简体   繁体   English

如何在列表列表中获取相同值的所有出现的索引列表?

[英]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. 我需要一个方法来获取包含某些特定值的所有元素的索引的列表,例如“3”。 So for value of '3' such list of indexes should be 所以对于'3'的值,这样的索引列表应该是

[[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 更新 :我们可以在同一个子列表中有几个寻求值的实例(在我们的例子中为'3'),例如

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]] . 所以期望的输出将是[[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: 假设值在每个子列表中出现一次,您可以使用以下函数,该函数使用内置enumerate函数和列表推导:

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]]

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

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