[英]How to replace elements in list with random number
首先,我是一个 python 初学者,只是坚持简单的事情。
我想根据我在另一个列表中的值,用随机创建的数字(按索引)替换列表中的一些元素。
预计 output 将类似于:[3,2,2,1,3]
我在下面的代码完全不能按应有的方式工作。
ori = [4,1,2,1,3] # some elements inside need to be changed
num_list = [2,1,1,1] # numbers that represent index in ori
import random
for num in range(len(num_list)):
ori[num-1]= random.randint(1,4)
# I want to replace element with previous one from given index
print(ori)
我不知道你想做什么,但这段代码似乎很好。 为什么 num_list 包含数字“1”3次? 在这段代码中,它将 ori[1] 替换为一个随机数 3 次......好吧,ori[2] 将被随机化一次。
ori = [4,1,2,1,3] # some elements inside need to be changed
num_list = [2,1,1,1] # numbers that represent index in ori
import random
for num in num_list:
ori[num]= random.randint(1,4)
print(ori)
您遇到的问题是您声明的num
变量只是 num_list 中的num_list
,因此您将在此处更改位置0, 1, 2, 3
ori
(这将由您的range
表示)。
你会像这样修复你的代码:
ori = [4,1,2,1,3] # some elements inside need to be changed
num_list = [2,1,1,1] # numbers that represent index in ori
import random
for num in num_list:
ori[num-1]= random.randint(1,4)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.