我有 2 个嵌套列表,我想编写一些代码来遍历两个列表中的每个子列表,并将两个列表中一起出现的所有元素分组在一起。我正在从事的项目实际上有巨大的嵌套列表,所以我创建了以下2个列表来稍微简化问题(我只有一年的Python经验)。如果可以创建一个函数将这两个列表中的元素组合在一起,我就可以将该函数应用到实际项目中。这个问题可能类似于:Find items that appear together on multiple lists , 但我无法理解该问题中编写的代码,正如我所说,我对 python 比较陌生。
my_list = [['a', 'd', 'l'], ['c', 'e', 't'], ['q', 'x'], ['p', 'f', 'd', 'k']
sec_list = [['f', 'd', 'w', 'a'], ['c', 'e', 'u', 'h'], ['q', 'x', 'd', 'z'], ['p', 'k']]
##The output should be something like:
[['a', 'd'], ['c', 'e'], ['q', 'x'], ['p', 'k'], ['f', 'd']]```
Thanks
最佳答案
您可以使用 zip
迭代两个序列并查找具有集合交集的公共(public)元素。请注意,您的代码在 my_list
my_list = [['a', 'd', 'l'], ['c', 'e', 't'], ['q', 'x'], ['p', 'f', 'd', 'k']]
sec_list = [['f', 'd', 'w', 'a'], ['c', 'e', 'u', 'h'], ['q', 'x', 'd', 'z'], ['p', 'k']]
# each item of my_list and sec_list are lists
# zip allows parallel iteration so l1 and l2 are the pairs of inner lists
# sets are designed for tasks like finding common elements
# the & sign is python for set intersection
matches = []
for l1, l2 in zip(my_list, sec_list):
matches.append(list(set(l1) & set(l2)))
这可以合并到列表理解中
my_list = [['a', 'd', 'l'], ['c', 'e', 't'], ['q', 'x'], ['p', 'f', 'd', 'k']]
sec_list = [['f', 'd', 'w', 'a'], ['c', 'e', 'u', 'h'], ['q', 'x', 'd', 'z'], ['p', 'k']]
matches = [list(set(l1) & set(l2)) for l1, l2 in zip(my_list, sec_list)]
关于python - 将一起出现在单独列表中的项目分组在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67234279/