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



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

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

注意:不要调用你的变量,list它隐藏了python的内置list类型。

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']

您可以在如下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']

如果我理解正确,您希望将一些元素移动到另一个数组。假设您要移动 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的分配,但使用 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']
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 并将弹出的值提供给目标列表

随机选择。

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

list.append( other_list.pop(( (

在一行中,它从 other_list 中弹出一个值并附加到列表对象

最新更新