搜索列表列表中某些元素的索引

时间:2021-06-05 10:10:29

标签: python list

test_list =[[[0,0,0,1],[0,0,0,3],[0,0,0,5],[0,0,0,6]],[[0,0,0,4]],[[0,0,0,0],[0,0,0,1]]]

check_for_test = [6,4,1]

我想在 test_list 中找到包含 check_for_test 元素的列表的索引。

test_list 和 check_for_test 已经排序,因此 check_for_test 中的值 6 只能出现在 test_list 的第一部分 [[0,0,0,1],[0,0,0,3],[0,0,0,5],[0,0,0,6]]

同样适用于只能出现在第二部分 [[0,0,0,4]] 中的值 4 和只能出现在 test_list 的第三部分 [[0,0,0,0],[0,0,0,1]] 中的值 1。

我的方法:

def index(source_list, to_find):
    index_finder = []
    for lists in test_list:
        index_finder.append([(i, item_list.index(to_find)) for i, item_list in enumerate(source_list) if to_find in item_list])
    return index_finder

deep_index = index(test_list, check_for_test)
print(deep_index)

电流输出:

[[], [], []]

期望的输出:

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

1 个答案:

答案 0 :(得分:0)

你可能想用这个

def index(seq, target):
    res = []
    for (i_idx, i), t in zip(enumerate(seq), target):
        for j_idx, j in enumerate(i):
            if t in j:
                res.append([(i_idx, j_idx)])
                break
    return res

或者这个嵌套列表推导式(相同的输出,但由于缺少 break,性能不完全相同)。

def index(seq, target):
    return [[(i_idx, j_idx)] for (i_idx, i), t in zip(enumerate(seq), target) for j_idx, j in enumerate(i) if t in j]

对于您显示的输入

test_list = [[[0,0,0,1],[0,0,0,3],[0,0,0,5],[0,0,0,6]],[[0,0,0,4]],[[0,0,0,0],[0,0,0,1]]]

check_for_test = [6,4,1]

print(index(test_list, check_for_test))

输出

[[(0, 3)], [(1, 0)], [(2, 1)]]
相关问题