level 3
钟丁葵川爱半沐2F
楼主
from itertools import combinations
def combine(temp_list, n):
'''根据n获得列表中的所有可能组合(n个元素为一组)'''
temp_list2 = []
for c in combinations(temp_list, n):
temp_list2.append(c)
return temp_list2
list1 = ['a', 'b', 'c','d' ]
end_list = []
for i in range(len(list1)):
if i>1:
end_list.extend(combine(list1, i))
last_list=[]
for k in end_list:
last_list.append(''.join(k))
print(last_list)
打印出来 的结果是:
['ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd']
其中没有‘ba','ca','cb'等,也就是说貌似combinations方法去掉了字符相同但顺序不一样的,如果想要字符元素相同但顺序不一样的也加进这个列表中,应该如何改代码?
2021年01月07日 19点01分
1
def combine(temp_list, n):
'''根据n获得列表中的所有可能组合(n个元素为一组)'''
temp_list2 = []
for c in combinations(temp_list, n):
temp_list2.append(c)
return temp_list2
list1 = ['a', 'b', 'c','d' ]
end_list = []
for i in range(len(list1)):
if i>1:
end_list.extend(combine(list1, i))
last_list=[]
for k in end_list:
last_list.append(''.join(k))
print(last_list)
打印出来 的结果是:
['ab', 'ac', 'ad', 'bc', 'bd', 'cd', 'abc', 'abd', 'acd', 'bcd']
其中没有‘ba','ca','cb'等,也就是说貌似combinations方法去掉了字符相同但顺序不一样的,如果想要字符元素相同但顺序不一样的也加进这个列表中,应该如何改代码?
