Python: shuffling list, but keeping some elements frozen

后端 未结 5 722
隐瞒了意图╮
隐瞒了意图╮ 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:38

    Overengineered solution: create a wrapper class that contains indexes of the unfreezed elements and emulates a list, and make sure the setter writes to the original list:

    class IndexedFilterList:
        def __init__(self, originalList, filterFunc):
            self.originalList = originalList
            self.indexes = [i for i, x in enumerate(originalList) if filterFunc(x)]
    
        def __len__(self):
            return len(self.indexes)
    
        def __getitem__(self, i):
            return self.originalList[self.indexes[i]]
    
        def __setitem__(self, i, value):
            self.originalList[self.indexes[i]] = value
    

    And call:

    random.shuffle(IndexedFilterList(mylist, lambda c: not c.freeze))
    

提交回复
热议问题