在基于嵌套序列元素的itertools.combinations中没有重复?

时间:2016-03-08 14:11:54

标签: python python-3.x itertools

source=[['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f',3]]
target=[list(x) for x in itertools.combinations(source,3)]
for i in target: print(i)

[['a', 1], ['b', 1], ['d', 2]]
[['a', 1], ['b', 1], ['e', 2]]
[['a', 1], ['b', 1], ['f', 3]]
[['a', 1], ['d', 2], ['e', 2]]
[['a', 1], ['d', 2], ['f', 3]]
[['a', 1], ['e', 2], ['f', 3]]
[['b', 1], ['d', 2], ['e', 2]]
[['b', 1], ['d', 2], ['f', 3]]
[['b', 1], ['e', 2], ['f', 3]]
[['d', 2], ['e', 2], ['f', 3]]

我可以让嵌套序列元素不重复itertools.combinations吗?在这种情况下,每个嵌套序列的元素[1]产生:

[['a', 1], ['d', 2], ['f', 3]]
[['a', 1], ['e', 2], ['f', 3]]
[['b', 1], ['d', 2], ['f', 3]]
[['b', 1], ['e', 2], ['f', 3]]

2 个答案:

答案 0 :(得分:0)

将输入列表拆分为单独的组,然后生成他们的产品。如果您的输入按第二个参数排序,则可以使用itertools.groupby()

from itertools import groupby, product
from operator import itemgetter

source = [['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f', 3]]
grouped = (list(group) for key, group in groupby(source, key=itemgetter(1)))
for combo in product(*grouped):
    print(list(combo))

如果输入未按第二个参数排序,则使用字典对它们进行分组:

source = [['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f', 3]]
groups = {}
for item in source:
    groups.setdefault(item[1], []).append(item)
grouped = [group for key, group in sorted(groups.items())]

我假设您想要对相同的第二个值进行排序以通知最终输出顺序。

答案 1 :(得分:0)

您可以编写一个过滤结果的生成器:

import itertools

def my_combinations(*args, **kw):
    for result in itertools.combinations(*args, **kw):
        _,l = zip(*result)
        if len(l) == len(set(l)):
            yield result

source=[['a', 1], ['b', 1], ['d', 2], ['e', 2], ['f',3]]
target=[list(x) for x in my_combinations(source,3)]
for i in target: print(i)