首页 > 解决方案 > 如何将一个列表中的值随机替换为另一个列表中的值?

问题描述

我一直在尝试这样做,但没有结果,以下是我的代码。所以我有一个包含 100 个数字的列表,分为两半,现在根据用户的选择,我必须将一个列表的值与另一个列表的值进行变异,

pop_size = []
c1 = 0
c2 = 0
u1 = 0.5
seed(1)
for i in range(0,100):
  x= randint(1,10)
  pop_size.append(x)
s1 = np.array(pop_size[:50])
s2 = np.array(pop_size[50:])



choice_var = input('Choose a species no 0 or 1')
if choice_var == 0 :
  indx1 = randint(0, len(s1)-1)
  s1[indx1] = choice(s2)

但是没有结果,我将不胜感激

标签: pythonlist

解决方案


试试这个,我已经测试过了,它正在运行。

import numpy as np
import random

pop_size = []
c1 = 0
c2 = 0
u1 = 0.5
random.seed(1)
for i in range(0,100):
  x= random.randint(1,10)
  pop_size.append(x)
s1 = np.array(pop_size[:50])
print(s1)
s2 = np.array(pop_size[50:])
#print(s2)



choice_var = int(input('Choose a species no 0 or 1'))
#choice_var = int(0)
if choice_var == 0 :
  indx1 = random.randint(0, len(s1)-1)
  print(indx1)
  print(random.choice(s2))
  s1[indx1] = random.choice(s2)

print(s1)

推荐阅读