简体   繁体   English

在迭代中将列表与其他列表进行比较,并在 Python 中的嵌套列表中返回差异

[英]Compare a list with other lists in iteration and return difference in a nested list in Python

I have a list like this:我有一个这样的清单:

my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]

and I want to compare its items with another list:我想将其项目与另一个列表进行比较:

main_list = ["a", "b", "f", "d"]

And I want to return the indexes that they differ.我想返回它们不同的索引。 My code so far looks like this:到目前为止,我的代码如下所示:

differences = []
my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]
main_list = ["a", "b", "f", "d"]

for i in range(len(my_list)):
    for index, (first, second) in enumerate(zip(my_list[i], main_list), start=1):
        if first != second:
            differences.append(index)
print(differences)

With the above code I get this output:通过上面的代码,我得到了这个输出:

[3, 2, 3, 4, 1, 2]

Which is exactly the indices the main list differs with the original list.这正是主列表与原始列表不同的索引。 However I would like to get this list as an output, which gives me a nested list of which each index is the indices the main list differs with my_list[0], then with my_list[1] and so on:但是我想得到这个列表作为输出,它给了我一个嵌套列表,其中每个索引是主列表与 my_list[0] 不同的索引,然后与 my_list[1] 等等:

[[3], [2], [3, 4], [1, 2]]

I would appreciate some help on modifying the code to get the ideal output.我很感激在修改代码以获得理想输出方面的一些帮助。 Thanks!谢谢!

my_list = [['a', 'b', 'c', 'd'], ['a', 'e', 'f', 'd'], ['a', 'b', 'c', 'g'], ['d', 'e', 'f', 'd']]
main_list = ["a", "b", "f", "d"]

out = []
for subl in my_list:
    out.append([i for i, (a, b) in enumerate(zip(subl, main_list), 1) if a != b])

print(out)

Prints:印刷:

[[3], [2], [3, 4], [1, 2]]

Or one liner:或一个班轮:

out = [[i for i, (a, b) in enumerate(zip(subl, main_list), 1) if a != b] for subl in my_list]
print(out)

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

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