python - 将一起出现在单独列表中的项目分组在一起

标签 python list grouping

我有 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/

相关文章:

python - python中alpha排序最快的列表

python - 如何转置 sympy 矩阵

c# - 如何删除计数最低的子列表并保留主列表中计数最高的子列表?

python - 使用 Python 查找字符串中列表出现的次数

mysql按天分组

perl - perl 正则表达式中捕获组的最大数量

python - 在一行中捕获多个异常( block 除外)

python - 带有 Python3 和 Gtk3 的 MVC

python - 仅查找列表中的唯一坐标

python - 在 Pandas 中,如何在 groupby.agg() 方法中应用 2 个自定义公式?