[英]Generating a list of random permutations of another list
So, I'm trying to tackle the TSP with a Genetic Algorithm. 因此,我正在尝试使用遗传算法解决TSP。 To do that I need to create a population pool.
为此,我需要创建一个人口池。 What I wan't to accomplish is to create a list of random permutations that will represent a population pool.
我要完成的工作是创建一个随机置换的列表,该列表将表示总体池。 I'm trying to do this using random.shuffle.
我正在尝试使用random.shuffle做到这一点。 Here's my code that should handle that part.
这是我应该处理的部分代码。 Cities is a list of cities and routes is where I want to keep the population pool (a list of N random permutations):
城市是城市列表,我想保留人口数量的路线(N个随机排列的列表):
for x in range(n):
random.shuffle(cities)
routes.append(cities)
What happens is that it just appends the same permutation n times. 发生的事情是,它只是将相同的排列附加了n次。 Anybody have any idea about what I might be missing?
有人对我可能会缺少的东西有任何想法吗?
shuffle
modifies the list in-place. shuffle
修改列表。 you need to add a copy of the list to your routes
; 您需要将列表的副本添加到您的
routes
; otherwise a reference to the same list is added which will be in its last shuffled state. 否则,将添加对同一列表的引用,该列表将处于其最后的混洗状态。
for x in range(n):
random.shuffle(cities)
routes.append(cities.copy())
import random
print [random.sample(cities,n) for i in xrange(n)]
You can try this. 你可以试试看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.