Python: shuffling list, but keeping some elements frozen

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

    One solution:

    def fixed_shuffle(lst):
        unfrozen_indices, unfrozen_subset = zip(*[(i, e) for i, e in enumerate(lst)
                                                if not e.freeze])
        unfrozen_indices = list(unfrozen_indices)
        random.shuffle(unfrozen_indices)
        for i, e in zip(unfrozen_indices, unfrozen_subset):
            lst[i] = e
    

    NOTE: If lst is a numpy array instead of a regular list, this can be a bit simpler:

    def fixed_shuffle_numpy(lst):
        unfrozen_indices = [i for i, e in enumerate(lst) if not e.freeze]
        unfrozen_set = lst[unfrozen_indices]
        random.shuffle(unfrozen_set)
        lst[unfrozen_indices] = unfrozen_set
    

    An example of its usage:

    class CAnswer:
        def __init__(self, x, freeze=False):
            self.x = x
            self.freeze = freeze
    
        def __cmp__(self, other):
            return self.x.__cmp__(other.x)
    
        def __repr__(self):
            return "" % self.x
    
    
    lst = [CAnswer(3), CAnswer(2), CAnswer(0, True), CAnswer(1), CAnswer(5),
           CAnswer(9, True), CAnswer(4)]
    
    fixed_shuffle(lst)
    

提交回复
热议问题