我试图弄清楚如何基于一个元素获取列表列表的组合。
所以假设我有这个列表列表
[["blue", 1], ["blue", 3], ["red", 6], ["green", 5]]
我如何在python中获得这些组合:
[["blue", 1], ["red", 6], ["green", 5]], [["blue", 3], ["red", 6], ["green", 5]]
答案 0 :(得分:0)
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]]]