python shuffle这样的位置将永远不会重复 [英] python shuffle such that position will never repeat
问题描述
我想对列表进行随机混洗,但有一个条件:混洗后,元素永远不能处于相同的原始位置.
I'd like to do a random shuffle of a list but with one condition: an element can never be in the same original position after the shuffle.
在python中是否有一种单行方法来执行此操作?
Is there a one line way to do such in python for a list?
示例:
list_ex = [1,2,3]
以下每个随机排列的列表在随机排列之后应具有相同的采样概率:
each of the following shuffled lists should have the same probability of being sampled after the shuffle:
list_ex_shuffled = [2,3,1]
list_ex_shuffled = [3,1,2]
,但不允许排列[1,2,3],[1,3,2],[2,1,3]和[3,2,1],因为它们全部重复元素位置之一
but the permutations [1,2,3], [1,3,2], [2,1,3] and [3,2,1] are not allowed since all of them repeat one of the elements positions.
注意:list_ex中的每个元素都是唯一的ID.不允许重复相同的元素.
NOTE: Each element in the list_ex is a unique id. No repetition of the same element is allowed.
有什么想法吗?谢谢!
推荐答案
在循环中随机化并不断拒绝结果,直到满足您的条件为止:
Randomize in a loop and keep rejecting the results until your condition is satisfied:
import random
def shuffle_list(some_list):
randomized_list = some_list[:]
while True:
random.shuffle(randomized_list)
for a, b in zip(some_list, randomized_list):
if a == b:
break
else:
return randomized_list
这篇关于python shuffle这样的位置将永远不会重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!