在python中获取所有唯一组合

时间:2018-07-05 22:46:48

标签: python combinations

我试图弄清楚如何基于一个元素获取列表列表的组合。

所以假设我有这个列表列表

    [["blue", 1], ["blue", 3], ["red", 6], ["green", 5]] 

我如何在python中获得这些组合:

    [["blue", 1], ["red", 6], ["green", 5]], [["blue", 3], ["red", 6], ["green", 5]]

1 个答案:

答案 0 :(得分:0)

这可以在groupbyproduct的帮助下完成:

data = [["blue", 1], ["blue", 3], ["red", 6], ["green", 5]]
groups = []
for k, g in itertools.groupby(data, key=lambda item: item[0]):
    groups.append(list(g))
print(list(itertools.product(*groups)))
# [(['blue', 1], ['red', 6], ['green', 5]), (['blue', 3], ['red', 6], ['green', 5])]

# just for understanding how it works:
print(groups)
# [[['blue', 1], ['blue', 3]], [['red', 6]], [['green', 5]]]