Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列表随机分成两个或三个项目的块_Python_List_Random_Chunks - Fatal编程技术网

Python 将列表随机分成两个或三个项目的块

Python 将列表随机分成两个或三个项目的块,python,list,random,chunks,Python,List,Random,Chunks,我遇到了一个问题,将列表分成不同大小的块。我想要一个列表,随机分成2对或3对 例如: L = [1,1,1,1,1,1,1,1,1,1,1,1] 我想得到一些东西,比如: L2 = [(1,1,1),(1,1),(1,1),(1,1,1),(1,1)] 但我希望这是随机的,这样每次运行代码时,对和三元组的分布都会发生变化。将len(L)分解为2和3的块,然后使用循环来划分列表 import numpy as np def rand23(): return np.random.ran

我遇到了一个问题,将列表分成不同大小的块。我想要一个列表,随机分成2对或3对

例如:

L = [1,1,1,1,1,1,1,1,1,1,1,1]
我想得到一些东西,比如:

L2 = [(1,1,1),(1,1),(1,1),(1,1,1),(1,1)]
但我希望这是随机的,这样每次运行代码时,对和三元组的分布都会发生变化。

len(L)
分解为2和3的块,然后使用循环来划分列表

import numpy as np

def rand23():
    return np.random.randint(2,4)

def get_chunk(sz):
    rem = sz
    ch = []
    while ( rem > 0 ):
        if ( rem <= 3 ): #if <= 3 add what is left in the chunk (exit condition)
            ch.append(rem)
            rem = 0
            break
        elif ( rem == 4 ): #4 is the only edge case here
            ch.append(2)
            ch.append(2)
            rem = 0
            break
        else:
            ch.append(rand23())
            rem -= ch[-1]

    return ch

L = [1,1,1,1,1,1,1,1,1,1,1,1]
ch = get_chunk(len(L))
L2 = []
count = 0
#Divide the list into chunks based on ch
for c in ch:
    L2.append(tuple(L[count:count+c]))
    count += c

print L2

PS:您还可以递归实现
get_chunk()

有很多方法可以解决这个问题,也许您可以编写一个生成器,根据
size
函数返回大小的块:

import random

def take_chunked(i, size):
    idx = 0
    while idx < len(i):
        s = size(i[idx:])
        yield i[idx:idx+s]
        idx += s

def size_fun(i):
    if len(i) == 4:
        return 2
    if len(i) <= 3:
        return len(i)

    return random.randint(2,3)
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
此版本将保证块大小为2或3,只要列表中有足够的项

希望这有帮助

步骤1:使用随机模块生成随机数

步骤2:使用随机数决定是成对还是2(偶数随机数)/3(如果随机数是nt偶数)

第三步:编码

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
从随机导入随机
def选择器():
s=int(随机()*100)
返回值(s/2)=0
L=[1代表范围(30)内的i]
L2=[]
而我:
如果选择器():
tmp=2
其他:
tmp=3
#打印tmp
如果tmp>0且len(L)>=tmp:
L2.追加([L.pop()表示范围内的i(tmp)])
如果len(L)<3:
L2.追加(集合(L))
L=[]
打印L,L2

作为更通用的方法,您可以使用以下功能:

import random

def take_chunked(i, size):
    idx = 0
    while idx < len(i):
        s = size(i[idx:])
        yield i[idx:idx+s]
        idx += s

def size_fun(i):
    if len(i) == 4:
        return 2
    if len(i) <= 3:
        return len(i)

    return random.randint(2,3)
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
说明: 此功能由到个子功能组成。第一个是chunk_creator,它的工作是根据列表的长度创建所需的块,并将它们作为迭代器返回。注意,结束值是
total
变量,它是前面的块的总和


第二个函数(
chunk\u finder
)将通过一个无限循环(
itertools.count()
)来为我们找到所需的块,并检查
total
的值是否与输入列表的长度相等。

这个函数相当简单,可以做到:-)

随机导入
L=[1,1,1,1,1,1,1,1,1,1,1,1,1]
L2=列表()
i=0
j=random.randint(2,3)
而我
是的,我添加了一条关于这个问题的评论。为了解决这个问题,我进行了更新,使用了一个不太优雅的
size\u-fun
答案的可能副本,那里的答案非常优雅。但对于这种特殊情况,当列表可以单独拆分为2和3的倍数时,它们有时会导致一个包含1个元素的块。例如:当使用
minu chunk=2
maxchunk=3运行时,在其中一次迭代中,接受的答案给出了L2的
[[1,1],[1,1,1],[1,1,1],[1]
,这将始终给出相同的结果。OP要求一个随机的配对和三元组序列。是的。后来才意识到。更正答案。
>>> L = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] 
>>> my_split(L, (2, 3))
... [[1, 1], [1, 1], [1, 1], [1, 1, 1], [1, 1, 1]]
>>> my_split(L, (2, 3))
... [[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]
import random

L = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
L2 = list()

i = 0
j = random.randint(2, 3)

while i < len(L):
    chunk = L[i:j]
    L2.append(chunk)
    i = j
    if len(L) - i == 4:  # case: 4 elements left in L
        j = i + 2
    elif len(L) - i < 4:  # case: 2 or 3 elements left in L
        j = len(L)
    else:
        j = i + random.randint(2, 3)

print L
print L2