Generating a list of random permutations of another list

孤人 提交于 2020-02-07 18:39:32

问题


So, I'm trying to tackle the TSP with a Genetic Algorithm. 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. 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):

for x in range(n):
    random.shuffle(cities)
    routes.append(cities)

What happens is that it just appends the same permutation n times. Anybody have any idea about what I might be missing?


回答1:


shuffle modifies the list in-place. you need to add a copy of the list to your 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())



回答2:


import random
print [random.sample(cities,n) for i in xrange(n)]

You can try this.



来源:https://stackoverflow.com/questions/33400584/generating-a-list-of-random-permutations-of-another-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!