from random import random
def selector():
s = int(random() * 100 )
return (s/2) == 0
L = [1 for i in range(30)]
L2 = []
while L:
if selector():
tmp = 2
else:
tmp = 3
#print tmp
if tmp > 0 and len(L) >= tmp:
L2.append( [ L.pop() for i in range(tmp)] )
if len(L) < 3:
L2.append(set(L))
L = []
print L, L2
from itertools import count
import random
def my_split(lst, chunks):
def chunk_creator():
total = 0
while total <= len(lst):
x = random.choice(chunks)
yield L[total: x + total]
total += x
yield total - x
def chunk_finder():
for _ in count():
chunk = list(chunk_creator())
total = chunk.pop(-1)
if total == len(L):
return chunk[:-1]
if max(chunks) <= len(L):
return chunk_finder()
else:
return None
希望这有帮助
步骤1:使用随机模块生成随机数
步骤2:使用随机数决定是成对还是2(偶数随机数)/3(如果随机数是nt偶数)
第三步:编码
有很多方法可以解决这个问题,也许您可以编写一个生成器,根据
size
函数返回大小的块:输出:
此版本将保证块大小为2或3,只要列表中有足够的项
作为更通用的方法,您可以使用以下功能:
演示:
说明:
此功能由到个子功能组成。第一个是chunk_creator,它的工作是根据列表的长度创建所需的块,并将它们作为迭代器返回。注意,结束值是
total
变量,它是前面块的总和第二个函数(
chunk_finder
)将通过遍历无限循环(itertools.count()
)并检查total
的值是否等于输入列表的长度来为我们找到所需的块相关问题 更多 >
编程相关推荐