而不是通過鍵上的嵌套循環,將所有值傳遞到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')]
謝謝!這正是我想要的。 –