3

我有一份清单,就像这样,

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)))

有没有更简单,更蟒蛇的方式!

4

3 回答 3

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']
于 2013-02-21T01:13:18.000 回答
4

迭代工具模块:

>>> import itertools
>>> map('-'.join, itertools.combinations(a, 2))
['dog-cat', 'dog-mouse', 'cat-mouse']
于 2013-02-21T01:12:09.437 回答
1

itertools肯定是去这里的方式。如果您只想使用内置插件执行此操作,请使用:

a = ['dog','cat','mouse']
ans = [x + '-' + y for x in a for y in a if x < y]
于 2013-02-21T02:17:43.807 回答