关于随机模块的questions方法,栈溢出上有相当多的random.shuffle。
让我对shuffle感到不快的是它在原地移动,而不是返回一个被洗牌的副本。
请注意,洗牌工作到位,并返回无。
因此,类似的表达式
for index, (parent1, parent2) in enumerate(zip(sorted(population)[::2], shuffle(population)[1::2])):别工作了。写它带有副作用似乎不必要地冗长:
other_half = population[1::2]
random.shuffle(other_half)
for index, (parent1, parent2) in enumerate(zip(sorted(population)[::2], other_half):从功能上来说,什么是节奏曲?
发布于 2017-11-06 11:57:53
一个很好的选择是random.sample,k是列表中的len:
import random
li = [1, 2, 3, 4, 5]
for _ in range(4): # showing we get a new, 'shuffled' list
print(random.sample(li, len(li)))
# [5, 2, 3, 1, 4]
# [1, 5, 4, 3, 2]
# [4, 2, 5, 1, 3]
# [4, 2, 3, 5, 1]发布于 2017-11-06 12:01:50
https://stackoverflow.com/questions/47136434
复制相似问题