[英]Select all the combinations of 8 elements from a given list
I have a list of 27 elements. 我列出了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]
I need to find all the combinations of selecting 8 elements from the list. 我需要找到从列表中选择8个元素的所有组合。 So far I have found an algorithm as below.
到目前为止,我发现了一种如下算法。
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)
Any suggestion would be really helpful 任何建议都会很有帮助
Edit- 编辑-
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
What I want to do is to get combinations of 1s and 0s of 28 length pattern where only 8 bits are 0s and I need to discard combinations with 8,7,6,5,4 or 3 consecutive 0s.(First bit of the pattern is always 1) This method I have is really exhaustive. 我想做的是获得28个长度模式的1和0的组合,其中只有8位是0,我需要舍弃具有8、7、6、5、4或3个连续0的组合。(模式的第一位总是1)我拥有的这种方法真的很详尽。 (I'm new to python, please bear with my bad programming)Any better algorithm will be really great.
(我是python的新手,请接受我糟糕的编程知识)任何更好的算法都将非常棒。
There's a python inbuilt to find combinations. 有内置的python查找组合。 It's itertools.combinations .
这是itertools.combinations 。 This will give you a generator at which you can iterate over to get all the combinations -
这将为您提供一个生成器,您可以在该生成器上进行迭代以获取所有组合-
import itertools
for combi in itertools.combinations(str1, 8):
print combi
Or do a list
in front of it to get a list of tuples of all the combinations - 或在其前面做一个
list
以获取所有组合的元组列表-
combi = list(itertools.combinations(str1, 8))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.