Pythonic方法构建组合字符串

时间:2013-02-21 01:08:33

标签: python list-comprehension

我有一个列表,就像这样,

a = ['dog','cat','mouse']

我想构建一个列表,它是所有列表元素的组合,看起来像,

ans = ['cat-dog', 'cat-mouse','dog-mouse']

这就是我想出来的,

a = ['dog','cat','mouse']
ans = []
for l in (a):
    t= [sorted([l,x]) for x in a if x != l]
    ans.extend([x[0]+'-'+x[1] for x in t])
print list(set(sorted(ans)))

是否有更简单,更pythonic的方式!

3 个答案:

答案 0 :(得分:7)

订购有多重要?

>>> a = ['dog','cat','mouse']
>>> from itertools import combinations
>>> ['-'.join(el) for el in combinations(a, 2)]
['dog-cat', 'dog-mouse', 'cat-mouse']

或者,为了匹配你的例子:

>>> ['-'.join(el) for el in combinations(sorted(a), 2)]
['cat-dog', 'cat-mouse', 'dog-mouse']

答案 1 :(得分:4)

itertools模块:

>>> import itertools
>>> map('-'.join, itertools.combinations(a, 2))
['dog-cat', 'dog-mouse', 'cat-mouse']

答案 2 :(得分:1)

itertools肯定是走到这里的路。如果您只想使用内置功能,请使用:

a = ['dog','cat','mouse']
ans = [x + '-' + y for x in a for y in a if x < y]