列表值之间的组合

时间:2016-04-19 14:44:08

标签: python itertools

让我们说我有以下清单:

letters = ['a','b','c']
numbers = ['one','two']
others = ['here','there']

我想要所有值的所有可能的组合。我正在做以下事情:

from itertools import permutations
b = []
b.extend(letters)
b.extend(numbers)
b.extend(others)
result1 = list(permutations(b,2))

结果还可以。但我更想要的是了解'类型'的比赛。例如,结果应为:

('a','b','letters-letters')

('a','one','letters-numbers')
('one','a','letters-numbers')

我使用以下代码:

from itertools import product
result2=[]
result2.extend([x+('letter-letter',) for x in list(permutations(letters ,2))])
result2.extend([x+('number-number',) for x in list(permutations(numbers,2))])
result2.extend([x+('other-other',) for x in list(permutations(others,2))])
result2.extend([x+('number-letter',) for x in list(product(numbers,letters))])
result2.extend([x+('number-letter',) for x in list(product(letters,numbers))])   
result2.extend([x+('number-others',) for x in list(product(numbers,others))])  
result2.extend([x+('number-others',) for x in list(product(others,numbers))])   
result2.extend([x+('letters-others',) for x in list(product(letters,others))])    
result2.extend([x+('letters-others',) for x in list(product(others,letters))])   

有更快捷,更优雅的方式吗?

1 个答案:

答案 0 :(得分:3)

IIUC,关键是数据系列元素是元素的成员。例如:

from itertools import permutations

data = {'letters': ['a','b','c'],
        'numbers': ['one','two'],
        'others': ['here','there']}

poss = [(v,k) for k, vv in data.items() for v in vv]
results = (list(zip(*p)) for p in permutations(poss, 2))
results = [p[0] + ('-'.join(p[1]),) for p in results]

给了我

[('a', 'b', 'letters-letters'),
 ('a', 'c', 'letters-letters'),
 ('a', 'here', 'letters-others'),
 ...
 ('two', 'here', 'numbers-others'),
 ('two', 'there', 'numbers-others'),
 ('two', 'one', 'numbers-numbers')]

这是有效的,因为我们从poss开始看起来像

>>> poss[:3]
[('a', 'letters'), ('b', 'letters'), ('c', 'letters')]

然后从中选择两个元素,使用zip-star将每个选定的对转换为

>>> next(list(zip(*p)) for p in permutations(poss, 2))
[('a', 'b'), ('letters', 'letters')]