Python:随机混合两个列表

时间:2018-11-26 01:21:14

标签: python list random mutation

在将两个列表混合在一起以创建长度相同的新列表时遇到了麻烦。

到目前为止,我已经从一堆列表中随机选择了两个列表,称为父级1和父级2。这是到目前为止,但是output_list行不起作用。

parent1 = listname[random.randint(1,popsize)]
parent2 = listname[random.randint(1,popsize)]
output_list = random.choice(concatenate([parent1,parent2]), length, replace=False)
print(output_list)

我想要的结果是: 如果parent1 = [1,2,3,4,5]parent2 = [6,7,8,9,10] 那么可能的结果可能是[1,2,3,9,10][1,7,2,5,6][1,2,7,4,5]

有人有什么主意吗?

(上下文是两组基因,它们通过父母基因的混合繁殖形成一个孩子)

2 个答案:

答案 0 :(得分:4)

您可以在连接parent_1parent_2后使用random.shuffle,并选择与parent_1相同长度的切片:

import random

parent_1 = [1,2,3,4,5]
parent_2 = [6,7,8,9,10]

c = parent_1 + parent_2
random.shuffle(c)

result = c[:len(parent_1)]
print(result) # [4, 5, 10, 6, 9]

答案 1 :(得分:0)

构建遗传算法时,最好是来自父级的值在子数组中保持相同的索引,就像染色体中的基因一样。

您可以使用numpy来实现:

import numpy as np
male = np.random.choice(100, 5)   # array([25, 90, 25, 96, 91])
female = np.random.choice(100, 5) # array([98, 19, 17, 78, 29])
np.choose(np.random.choice(2, 5), [male, female])
# array([98, 19, 25, 96, 29])
np.choose(np.random.choice(2, 5), [male, female])
# array([25, 90, 25, 78, 29])