Python 如何将一个列表的多个随机值转移到另一个列表?
我不知道如何将一个列表中的多个(但不是全部)随机值转移到另一个列表中。我知道如何使用pop传输一个随机值,但我希望能够传输多个值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
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']