我不确定如何将列表中的随机,多个(但不是全部)值传输到另一个列表。我知道如何使用pop来传输一个随机值,但我希望能够做多个值。
mylist = ["1", "2", "3", "4", "5"]
x = list.pop(random.randint(0,len(mylist)))
答案 0 :(得分:2)
注意:请勿调用变量list
,它会隐藏list
类型内置的python内容。
lst = ["1", "2", "3", "4", "5"]
random
模块提供了随机化序列的机制,例如您可以使用random.shuffle()
:
In [1]:
random.shuffle(lst)
lst
Out[1]:
['3', '1', '2', '5', '4']
或创建新列表:
In [2]:
x = random.sample(lst, k=len(lst))
x
Out[2]:
['4', '5', '3', '2', '1']
答案 1 :(得分:0)
您可以在for-loop
中使用您的代码:
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']
答案 2 :(得分:0)
如果我理解正确,你想将一些元素移动到另一个数组。 假设你想要移动N个元素:
mylist = ["1", "2", "3", "4", "5"]
newlist = []
for i in range(N):
myrand = random.randint(0,len(mylist))
newlist.append(mylist.pop(myrand))
答案 3 :(得分:0)
与@ 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']
如果您还可以尝试np.random.choice
,它会为您提供更多选项(例如尺寸,有/无替换以及与每个条目相关的概率)。
lst = [str(x) for x in range(6) if x > 0]
new_lst = list(np.random.choice(lst, size=4, replace=False))
print(new_lst)
输出:
['4', '5', '3', '1']
答案 4 :(得分:-1)
import random
source = [1, 2, 3, 4, 5]
destination = []
n = 3 # i want to transfer 3 random numbers to another list
for _ in range(n):
destination.append(source.pop(random.choice(list(range(len(source)-1))
这将创建源的所有索引的列表 这样你就可以选择一个随机的方法来使用pop并将弹出的值提供给目的地列表
它从给定列表中选择一个随机值
在一行中,它从other_list中弹出一个值并附加到列表对象