Python:洗牌列表,但保持一些元素冻结 [英] Python: shuffling list, but keeping some elements frozen
问题描述
我有这样的问题:
有一个 CANswer
类的元素列表(不需要描述这个类),我需要对它进行洗牌,但有一个约束——列表中的一些元素有 CANswer.freeze
设置为 True
,这些元素不能被打乱,而是保持在它们原来的位置.所以,让我们说,对于给定的列表:
There is a list of elements of class CAnswer
(no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have CAnswer.freeze
set to True
, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a given list:
[a, b, c, d, e, f]
其中所有元素都是 CANswer
的实例,但是 c.freeze == True
,对于其他元素 freeze == False
,可能的结果可能是:
Where all elements are instances of CAnswer
, but c.freeze == True
, and for others freeze == False
, the possible outcome could be:
[e, a, c, f, b, d]
所以索引为 2 的元素仍然在它的位置上.
So element with index 2 is still on its position.
实现它的最佳算法是什么?
What is the best algorithm to achieve it?
先谢谢你:)
推荐答案
另一种解决方案:
# memorize position of fixed elements
fixed = [(pos, item) for (pos,item) in enumerate(items) if item.freeze]
# shuffle list
random.shuffle(items)
# swap fixed elements back to their original position
for pos, item in fixed:
index = items.index(item)
items[pos], items[index] = items[index], items[pos]
这篇关于Python:洗牌列表,但保持一些元素冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!