用Python的方式构建组合字符串

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

有没有更简单和更符合Pythonic的方式!
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']

如果有必要,sorted会处理它:['-'.join(c) for c in combinations(sorted(a),2)]会产生问题文本中给出的答案。 - Mark Reed
@MarkReed 我一定是想象错了“已排序的几个” :P - Jon Clements
你太快了,@JonClements。虽然谢谢你。 :) - Mark Reed

4

标准库中的itertools模块:

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

1

itertools无疑是这里的最佳选择。如果你只想使用内置函数,可以使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接