Python: shuffling list, but keeping some elements frozen

后端 未结 5 731
隐瞒了意图╮
隐瞒了意图╮ 2021-01-08 00:25

I\'ve such a problem:

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 -

5条回答
  •  清歌不尽
    2021-01-08 00:42

    Another solution:

    # 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]
    

提交回复
热议问题