Python 我可以将计数器反转为没有倍数的列表吗?

Python 我可以将计数器反转为没有倍数的列表吗?,python,sorting,counter,Python,Sorting,Counter,使用 什么习惯用法可以将集合计数器分配到一个列表中,其中每个列表中只显示一次集合计数器 [['a', 'b', 'c'],['b', 'c'],['b']] 我不知道你是否在寻找一条客轮,但这里有一条客轮: 代码: [sorted(y for y in z if y is not None) for z in it.izip_longest(*[[k] * l for k, l in c.items()])] from collections import Counter c

使用

什么习惯用法可以将集合计数器分配到一个列表中,其中每个列表中只显示一次集合计数器

[['a', 'b', 'c'],['b', 'c'],['b']]

我不知道你是否在寻找一条客轮,但这里有一条客轮:

代码:

[sorted(y for y in z if y is not None) 
       for z in it.izip_longest(*[[k] * l for k, l in c.items()])]
from collections import Counter
c = Counter({'b': 3, 'c': 2, 'a': 1})

import itertools as it
print([sorted(y for y in z if y is not None) 
       for z in it.izip_longest(*[[k] * l for k, l in c.items()])])
[['a', 'b', 'c'], ['b', 'c'], ['b']]
怎么做?

这里有两个关键点:

  • [k]*l
    给出了计数器键的列表,计数器值很长
  • izip_longest()
    将把列表放在一起,并对较短的列表填充“无”
  • 测试代码:

    [sorted(y for y in z if y is not None) 
           for z in it.izip_longest(*[[k] * l for k, l in c.items()])]
    
    from collections import Counter
    c = Counter({'b': 3, 'c': 2, 'a': 1})
    
    import itertools as it
    print([sorted(y for y in z if y is not None) 
           for z in it.izip_longest(*[[k] * l for k, l in c.items()])])
    
    [['a', 'b', 'c'], ['b', 'c'], ['b']]
    
    结果:

    [sorted(y for y in z if y is not None) 
           for z in it.izip_longest(*[[k] * l for k, l in c.items()])]
    
    from collections import Counter
    c = Counter({'b': 3, 'c': 2, 'a': 1})
    
    import itertools as it
    print([sorted(y for y in z if y is not None) 
           for z in it.izip_longest(*[[k] * l for k, l in c.items()])])
    
    [['a', 'b', 'c'], ['b', 'c'], ['b']]
    
    您可以尝试以下方法:

    import itertools
    
    the_dict = {'b': 3, 'c': 2, 'a': 1}
    
    the_frequencies  = [[a]*b for a, b in the_dict.items()]
    
    the_list = itertools.izip_longest(the_frequencies)
    
    the_final = map(list, list(itertools.izip_longest(*the_frequencies)))
    
    print [[i for i in b if i != None] for b in the_final]
    

    此解决方案使用itertools压缩包含在_频率中的列表,这些频率是通过将键列表乘以其相应值创建的。然后,izip用_频率中的元素行形成一个列表,如果当前迭代的计数大于列表列表中任何列表的长度,则不存储任何元素

    最终列表中的顺序重要吗?还是仅仅内容重要?集合计数器返回一个
    dict
    ,因此我认为我们在这一点上运气不佳。然而,这也是一个很好的问题——取两个带倍数的列表,并返回一个列表列表,每个列表不带倍数。注意,在Python 3.5中,izip_longest()现在是
    zip_longest()