生成两个参数元素的子集

时间:2016-07-03 12:59:49

标签: python list

我是python的新手,目前我正在使用函数生成列表中的子集。这是我需要回来的样本。

例如

  • 字符串:AECG
  • 子集:['AE', 'AC', 'AG', 'EC', 'EG', 'CG']

我正在考虑将字符串放入一个空列表然后在列表中播放,但它不起作用。你能帮忙吗〜

result=[]
s="AECG"

for i in s:
    result.append(i)
    for j in range (0,len(result)-1):
        for x in range (1,len(result)):
            subsets=result.append(j,x)
    print(subsets)

2 个答案:

答案 0 :(得分:4)

使用itertools.combinations

>>> import itertools
>>> list(itertools.combinations('AECG', 2))
[('A', 'E'), ('A', 'C'), ('A', 'G'), ('E', 'C'), ('E', 'G'), ('C', 'G')]
>>> [''.join(x) for x in itertools.combinations('AECG', 2)] # tuples -> strings
['AE', 'AC', 'AG', 'EC', 'EG', 'CG']

更新使用map和绑定方法''.join

>>> list(map("".join, itertools.combinations('AECG', 2)))
['AE', 'AC', 'AG', 'EC', 'EG', 'CG']

答案 1 :(得分:2)

为了完整起见,这里是没有itertools的解决方案

subsets=[]
s="AECG"

for i in range (len(s)):
    for j in range (i+1, len(s)):
          subsets.append(s[i]+s[j]) # append modifies the list
print(subsets)
相关问题