python - 如何使用约束对列表进行洗牌(与每个元素的索引相关)
问题描述
例如,有一个列表,[1,2,3]
具有约束使得混洗列表的每个元素不应与先前元素的位置重叠。为了解释清楚,假设之前的列表是[1,2,3]
,但经过改组后变为[1,3,2]
。对于这种情况,因为1
是两个列表的第一个元素,所以这不满足约束。满足该约束的输出将是[2,3,1]
和[3,1,2]
。
有没有办法在改组列表之前做出这个约束?
提前致谢。
解决方案
您可以通过旋转列表来完成此操作。例如, 和的[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]
推荐阅读
- flutter - 如果颤动中有条件,如何将元素添加到列中?
- c# - 查找给定日期时间在日期时间范围内的哪一周
- javascript - ConnectFunction 创建的组件中的元素类型无效
- docker - 在 Kubernetes 上启动 Spark 3.0 -- 拉取镜像时出错
- android - 如何在图表线android上方添加渐变颜色?
- ios - Xcode11禁用暗模式
- flutter - 如何绘制这样的自定义颤振边框?
- postgresql - 自定义功能:将对象插入表格
- java - spring batch 提供作业执行状态和步骤信息
- android - RatingBar - 当触摸 RatingBar 时,星星会被填满