Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/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数组错误在100种情况下发生1-3次_Python_Arrays - Fatal编程技术网

Python数组错误在100种情况下发生1-3次

Python数组错误在100种情况下发生1-3次,python,arrays,Python,Arrays,我有一个完整的部分工作的问题程序,函数应该从一个数组中选择n个随机项,然后将它们放到另一个数组中,如果数组n.1中有相同的元素,那么它不能在数组n.2中放置多个元素 代码: 例如,以数组a为例: a=['matt', 'john', 'peter', 'john', 'joseph', 'adam', 'steven', 'paul'] 并运行它,例如100次: for i in range(100): pick(4,a) 您会注意到,有些数组只包含3个元素,它们都应该是4个!所以我

我有一个完整的部分工作的问题程序,函数应该从一个数组中选择n个随机项,然后将它们放到另一个数组中,如果数组n.1中有相同的元素,那么它不能在数组n.2中放置多个元素

代码:

例如,以数组a为例:

a=['matt', 'john', 'peter', 'john', 'joseph', 'adam', 'steven', 'paul']
并运行它,例如100次:

for i in range(100):
    pick(4,a)
您会注意到,有些数组只包含3个元素,它们都应该是4个!所以我的问题是为什么会这样?

你想改变吗

for i in range(len(array))
## to
while len(array2) < n:
## or
while True:  ## infinite loop until the break statement is executed

为了避免让事情变得更清楚。

为什么要在rangelenarray中使用for i?这就为您获取唯一随机数的尝试次数设置了上限。@Mark Ransom谢谢!我想我不需要运行它超过数组n.1的长度。我已经将其更改为while lenarray!=它正在工作。愚蠢的错误,但谢谢你!如果制作输入数组的副本,请从副本中选择元素,然后从副本中删除所选元素;那么你最多只需要运行n次循环。谢谢你,是的,马克·拉姆森也写了它。我已经将其更改为:while lenarray!=N
for i in range(len(array))
## to
while len(array2) < n:
## or
while True:  ## infinite loop until the break statement is executed
    if len(array2) == n:
        break
    ## to
    if len(array2) == n:
        return array2