![](/img/trans.png)
[英]How to sequentially populate a list of given length from another list of elements and recursively find all possible combinations that satisfy?
[英]Select all the combinations of 8 elements from a given list
我列出了27個元素。
str1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
我需要找到從列表中選擇8個元素的所有組合。 到目前為止,我發現了一種如下算法。
def combi(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
任何建議都會很有幫助
編輯-
def getCombinations5(list1):
list1=list1
list2=[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]
#print list2
#str1='123456'
str1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27]
#print str1
list3=[]
for value in combi(str1,8):
#print '#############################'
#print list3
#print value
#print list2[int(value[0])]
list2[int(value[0])]=0
list2[int(value[1])]=0
list2[int(value[2])]=0
list2[int(value[3])]=0
list2[int(value[4])]=0
list2[int(value[5])]=0
list2[int(value[6])]=0
list2[int(value[7])]=0
#print list2
list3.append(list2[:])
#print list3
#print list3
list2[int(value[0])]=1
list2[int(value[1])]=1
list2[int(value[2])]=1
list2[int(value[3])]=1
list2[int(value[4])]=1
list2[int(value[5])]=1
list2[int(value[6])]=1
list2[int(value[7])]=1
#print '@@@@@@@@@@@@@@@@@'
#print len(list3)
#print list2
print len(list3)
list4=[]
for value in list3:
str2=''.join(str(e) for e in value)
if '00000000' in str2 or '0000000' in str2 or '000000' in str2 or '00000' in str2 or '0000' in str2:
continue
elif '000' in str2:
continue
else:
list0=list(str2)
#print list0
list0=map(int, list0)
list4.append(list0)
print list4
我想做的是獲得28個長度模式的1和0的組合,其中只有8位是0,我需要舍棄具有8、7、6、5、4或3個連續0的組合。(模式的第一位總是1)我擁有的這種方法真的很詳盡。 (我是python的新手,請接受我糟糕的編程知識)任何更好的算法都將非常棒。
有內置的python查找組合。 這是itertools.combinations 。 這將為您提供一個生成器,您可以在該生成器上進行迭代以獲取所有組合-
import itertools
for combi in itertools.combinations(str1, 8):
print combi
或在其前面做一個list
以獲取所有組合的元組列表-
combi = list(itertools.combinations(str1, 8))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.