在不同的项目之间随机播放列表项目

Shuffle a list items among dissimilar items

如何打乱列表项以保持相似项不打乱?例如。对于列表 'L',我想在独特的项目之间随机播放。

L=[a,a,b,b,c,c,d,d]

对于上面的列表,我想得到

shuffled_L=[c,c,a,a,d,d,b,b]

应用来自评论的@suddents_appearence方法

>>> import random
>>> import itertools
>>> from collections import Counter
>>> L=["a","a","b","b","c","c","d","d"]
>>> count=Counter(L)
>>> sample=random.sample(sorted(count),len(count))
>>> _shuffled_L=list(map(lambda x:[x]*count.get(x),sample))
>>> shuffled_L=list(itertools.chain.from_iterable(_shuffled_L))
>>> shuffled_L
['d', 'd', 'b', 'b', 'a', 'a', 'c', 'c']

分组为元组,打乱元组,再次展平列表:

>>> from itertools import groupby, chain
>>> from random import shuffle
>>> L = ["a", "a", "b", "b", "c", "c", "d", "d"]
>>> L_ = [tuple(v) for _, v in groupby(L)]
[('a', 'a'), ('b', 'b'), ('c', 'c'), ('d', 'd')]
>>> random.shuffle(L_)
[('b', 'b'), ('a', 'a'), ('d', 'd'), ('c', 'c')]
>>> list(chain.from_iterable(L_))
['b', 'b', 'a', 'a', 'd', 'd', 'c', 'c']

这假定原始 L 已经排序。如果不是,sort 它在 groupby 步骤之前。