【问题标题】:combination of elements of sets集合元素的组合
【发布时间】:2017-06-11 16:00:22
【问题描述】:

我有一本字典。

d = {
    'Cause Class': {'CC1', 'CC2'},
    'Cause Type': {'Ct1', 'Ct2', 'Ct3', 'Ct4'},
    'Incident Type': {'It1', 'It2', 'It3'}
} 

我想找到两个元素的组合,其中每个元素必须来自dict的不同键。

例如:('CC1', 'Ct1') 是这样一种组合,而 ('Ct1', 'Ct2') 不是。

我试过了

ksgg = []
for i in d:
    #print(i)
    for j in d:
        if i != j:
            ksgg.append(list(set(it.product(d[i],d[j]))))

但它给出了('CC1', 'Ct1')('Ct1', 'CC1') 作为两个不同的组合,但我只想要其中一个。

【问题讨论】:

    标签: python dictionary set combinations


    【解决方案1】:

    代替键的嵌套循环,将所有值传递给itertools.combinations();它会选择给定长度的独特组合:

    from itertools import combinations, product
    
    ksgg = []
    for set1, set2 in combinations(d.values(), 2):
        ksgg += product(set1, set2)
    

    对于您给定的字典,将创建以下组合:

    >>> from itertools import combinations, product
    >>> for set1, set2 in combinations(d, 2):
    ...     print(set1, set2, sep=' - ')
    ...
    Cause Class - Cause Type
    Cause Class - Incident Type
    Cause Type - Incident Type
    

    配对的确切顺序因字典顺序而异。

    完整演示:

    >>> ksgg = []
    >>> for set1, set2 in combinations(d.values(), 2):
    ...     ksgg += product(set1, set2)
    ...
    >>> from pprint import pprint
    >>> pprint(ksgg)
    [('CC1', 'Ct4'),
     ('CC1', 'Ct2'),
     ('CC1', 'Ct1'),
     ('CC1', 'Ct3'),
     ('CC2', 'Ct4'),
     ('CC2', 'Ct2'),
     ('CC2', 'Ct1'),
     ('CC2', 'Ct3'),
     ('CC1', 'It2'),
     ('CC1', 'It1'),
     ('CC1', 'It3'),
     ('CC2', 'It2'),
     ('CC2', 'It1'),
     ('CC2', 'It3'),
     ('Ct4', 'It2'),
     ('Ct4', 'It1'),
     ('Ct4', 'It3'),
     ('Ct2', 'It2'),
     ('Ct2', 'It1'),
     ('Ct2', 'It3'),
     ('Ct1', 'It2'),
     ('Ct1', 'It1'),
     ('Ct1', 'It3'),
     ('Ct3', 'It2'),
     ('Ct3', 'It1'),
     ('Ct3', 'It3')]
    

    【讨论】:

    • 谢谢!这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2014-08-13
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多