Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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 - Fatal编程技术网

Python 如何将一个列表的多个随机值转移到另一个列表?

Python 如何将一个列表的多个随机值转移到另一个列表?,python,Python,我不知道如何将一个列表中的多个(但不是全部)随机值转移到另一个列表中。我知道如何使用pop传输一个随机值,但我希望能够传输多个值 mylist = ["1", "2", "3", "4", "5"] x = list.pop(random.randint(0,len(mylist))) 您可以在for循环中使用代码,如: lst = ["1", "2", "3", "4", "5"] lst2 = [] for _ in xrange(len(lst)): lst2.append(ls

我不知道如何将一个列表中的多个(但不是全部)随机值转移到另一个列表中。我知道如何使用pop传输一个随机值,但我希望能够传输多个值

mylist = ["1", "2", "3", "4", "5"]
x = list.pop(random.randint(0,len(mylist)))

您可以在
for循环中使用代码,如:

lst = ["1", "2", "3", "4", "5"]
lst2 = []
for _ in xrange(len(lst)):
    lst2.append(lst.pop(random.randint(0, len(lst)-1)))
print lst2
输出:

['3', '2', '5', '4', '1']

注意:不要调用变量
list
它隐藏了python在
list
类型中的内置内容

lst = ["1", "2", "3", "4", "5"]
random
模块提供了随机化序列的机制,例如,您可以使用
random.shuffle()

或创建新列表:

In [2]:
x = random.sample(lst, k=len(lst))
x

Out[2]:
['4', '5', '3', '2', '1']
列表(范围(透镜(源))) 这将创建源文件的所有索引的列表 这样,您就可以选择一个使用pop的随机值,并将弹出的值提供给目标列表

随机选择 它从给定列表中选择一个随机值

list.append(other_list.pop())
在一行中,它从另一个列表中弹出一个值并附加到列表对象

如果我理解正确,您希望将一些元素移动到另一个数组。 假设要移动N个元素:

mylist = ["1", "2", "3", "4", "5"]
newlist = []
for i in range(N):
   myrand = random.randint(0,len(mylist))
   newlist.append(mylist.pop(myrand))

类似于@AChampion的apporach,但使用
numpy

import numpy as np

lst = [str(x) for x in range(6) if x > 0]
np.random.shuffle(lst)
print(lst)
输出:

['3', '1', '4', '5', '2']
['4', '5', '3', '1']
如果您还可以尝试
np.random.choice
,它为您提供了更多选项(例如大小、有/没有替换以及与每个条目相关的概率)

输出:

['3', '1', '4', '5', '2']
['4', '5', '3', '1']
这不管用。a)
list
对象没有
shuffle()
函数b)您已经重新定义了
shuffle
。c)
random.shuffle()
修改列表,因此
mylist.copy()
将被洗牌,但您尚未将变量分配给
mylist.copy()
,d)
random.shuffle()
返回
None
['4', '5', '3', '1']