无重复输入itertools.组合基于嵌套序列元素?

2024-04-19 02:02:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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.组合不按嵌套序列元素重复?在这种情况下,每个嵌套序列的元素[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]]

Tags: in元素sourcetargetfor情况序列list
2条回答

把你的输入列表分成不同的小组,然后生产他们的产品。如果输入按第二个参数排序,则可以使用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())]

在这里,我假设您希望对相同的第二个值进行排序,以通知最终的输出顺序。你知道吗

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

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)

相关问题 更多 >