加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Pythonic方法构建组合字符串

发布时间:2020-12-20 12:21:41 所属栏目:Python 来源:网络整理
导读:我有一个列表,像这样, a = ['dog','cat','mouse'] 我想构建一个列表,它是所有列表元素的组合,看起来像, ans = ['cat-dog','cat-mouse','dog-mouse'] 这就是我提出的, a = ['dog','mouse']ans = []for l in (a): t= [sorted([l,x]) for x in a if x != l] ans
我有一个列表,像这样,

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

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

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

这就是我提出的,

a = ['dog','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的方式!

解决方法

订购有多重要?

>>> a = ['dog','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','dog-mouse']

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读