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

2024-04-25 11:44:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题,将列表分成不同大小的块。我想要一个列表,随机分成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)]

但我希望这是随机的,这样每次运行代码时,对和三元组的分布都会发生变化


Tags: 代码列表三元组l2
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

有很多方法可以解决这个问题,也许您可以编写一个生成器,根据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)

输出:

>>> list(take_chunked("helloworld", size_fun))
['he', 'll', 'owo', 'rld']
>>> list(take_chunked("helloworld", size_fun))
['hel', 'low', 'or', 'ld']
>>> list(take_chunked("a", size_fun))
['a']
>>> list(take_chunked("", size_fun))
[]

此版本将保证块大小为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

演示:

>>> 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]]

说明:

此功能由到个子功能组成。第一个是chunk_creator,它的工作是根据列表的长度创建所需的块,并将它们作为迭代器返回。注意,结束值是total变量,它是前面块的总和

第二个函数(chunk_finder)将通过遍历无限循环(itertools.count())并检查total的值是否等于输入列表的长度来为我们找到所需的块

相关问题 更多 >