首页 > 解决方案 > 如何使用约束对列表进行洗牌(与每个元素的索引相关)

问题描述

例如,有一个列表,[1,2,3]具有约束使得混洗列表的每个元素不应与先前元素的位置重叠。为了解释清楚,假设之前的列表是[1,2,3],但经过改组后变为[1,3,2]。对于这种情况,因为1是两个列表的第一个元素,所以这不满足约束。满足该约束的输出将是[2,3,1][3,1,2]

有没有办法在改组列表之前做出这个约束?

提前致谢。

标签: pythonpython-3.xlistshuffle

解决方案


您可以通过旋转列表来完成此操作。例如, 和的[1, 2, 3]旋转。[3, 1, 2][2, 3, 1]

请注意,对于长度 > 3,旋转将是适合您的约束的所有可能洗牌的子集,但如果我理解正确,那对您有用。例如,使用 input [1, 2, 3, 4][4, 3, 2, 1]是有效的输出,但不是旋转。

collections.deque使其易于旋转,并且针对旋转进行了优化。

random.randrange()可用于随机化旋转计数。

import random
import collections

def random_rotation(lst):
    """
    Rotate a list by a random amount.

    Similar to "random.shuffle()", but ensures that all elements will move.
    """
    n = random.randrange(1, len(lst))
    d = collections.deque(lst)
    d.rotate(n)
    lst[:] = d  # Overwrite

L = [1, 2, 3, 4]
random_rotation(L)
print(L)

示例输出:

[2, 3, 4, 1]

推荐阅读