Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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_Arrays - Fatal编程技术网

如何对数组/列表中的块进行随机采样(替换),而不是使用python对列表中的单个元素进行采样

如何对数组/列表中的块进行随机采样(替换),而不是使用python对列表中的单个元素进行采样,python,arrays,Python,Arrays,我能够从列表中将列表拆分为块数组,如下面的python代码所示: def split_list(the_list, chunk_size): result_list = [] while the_list: result_list.append(the_list[:chunk_size]) the_list = the_list[chunk_size:] return result_list a_list = [1, 2, 3, 4, 5,

我能够从列表中将列表拆分为块数组,如下面的python代码所示:

def split_list(the_list, chunk_size):
    result_list = []
    while the_list:

result_list.append(the_list[:chunk_size])
            the_list = the_list[chunk_size:]

    return result_list

a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print split_list(a_list, 3)
这将产生块数组的以下结果:

# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
我还知道通过numpy.random.choice(即使更换)进行随机抽样,如下所示:

import numpy as np
a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
np.random.choice(a_list, size=20, 
replace=True)
这将产生以下结果:

#array([ 6,  9,  4,  9,  1,  1,  6, 10,  8,  5, 10,  6,  2,  6,  7,  1,  3,
    2,  7,  6])
我想要什么 我想用替换对数组中的块进行采样(而每个块的元素保持原样)

我期待得到一个代码,它将产生如下内容:

# [[7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [10], [1, 2, 3], [1, 2, 3], [10], [1, 2, 3], [7, 8, 9], [1, 2, 3], [1, 2, 3], [10], [4, 5, 6], [4, 5, 6], [10], [10], [7, 8, 9],, [1, 2, 3], [7, 8, 9]]

我自己选择了上面的chunk示例,我需要帮助获得一个可以工作的python代码来完成这项工作。

您可以确定列表中不同chunk的数量(示例中为4),然后随机选择所需的索引(示例中为0到3)

因此,你可以:

import math
import random

def random_chunk(lst, chunk_size):
    nb_chunks = int(math.ceil(len(lst)/chunk_size))
    choice = random.randrange(nb_chunks) # 0 <= choice < nb_chunks
    return lst[choice*chunk_size:(choice+1)*chunk_size]

a_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
out = [random_chunk(a_list, chunk_size=3) for _ in range(20)]

print(out)

# [[10], [7, 8, 9], [4, 5, 6], [4, 5, 6], [1, 2, 3], [7, 8, 9], [7, 8, 9], [4, 5, 6],
#  [10], [7, 8, 9], [10], [10], [10], [7, 8, 9], [10], [10], [10], [4, 5, 6], [4, 5, 6], [10]]
导入数学
随机输入
def随机块(lst,块大小):
nb_chunks=int(math.ceil(len(lst)/chunk_size))
choice=random.randrange(nb#U块)#0