首页 > 解决方案 > 有没有办法在 python 中使用这个标准修改列表?

问题描述

假设我们有一组有序的元素[a, b]

初始设置

[[1,5], [2,5], [3,5], [3,6], [4,5]]

由于我对4 个元素的集合感兴趣,并且我看到元素 2 和 3 具有相同的值a,我想知道如何编写一个从初始集合开始并执行以下操作的程序:

设置 1

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

设置 2

[[1,5], [2,5], [3,6], [4,5]]

例如,如果初始集合是:

[[1,5], [2,5], [3,5], [3,6], [4,5], [4,6]]

该程序应返回:

[[1,5], [2,5], [3,5], [4,5]]
[[1,5], [2,5], [3,5], [4,6]]
[[1,5], [2,5], [3,6], [4,5]]
[[1,5], [2,5], [3,6], [4,6]]

python有没有办法做到这一点?我曾尝试使用combinationsandpermutations模块,但在我看来,这对于任务的简单性来说太过分了。

非常感谢。

标签: pythonlistsortingsetcombinations

解决方案


按第一个元素分组,然后得到product

import collections, itertools

lst = [[1,5], [2,5], [3,5], [3,6], [4,5]]
d = collections.defaultdict(list)
for x in lst:
    d[x[0]].append(x)

res = list(itertools.product(*d.values()))                                    
# [([1, 5], [2, 5], [3, 5], [4, 5]),
#  ([1, 5], [2, 5], [3, 6], [4, 5])]

如果列表按第一个元素排序,您也可以groupby按照其他答案所示使用,然后获取那些的`product:

from itertools import product, groupby                                  
for x in product(*(list(g) for k, g in groupby(lst, key=lambda x: x[0]))): 
    print(x) 

推荐阅读