我有一个列表,就像这样:
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的方式!
sorted
会处理它:['-'.join(c) for c in combinations(sorted(a),2)]
会产生问题文本中给出的答案。 - Mark Reed