我有一个简单的数字字典及其各自的频率,我结合了两个列表:
elements = [1, 2, 3, 4, 5]
frequency = [5, 4, 3, 2, 1]
combined = {ele: freq for ele, freq in zip(elements, frequency)}
>>> print(combined)
{1: 5, 2: 4, 3: 3, 4: 2, 5: 1}
Run Code Online (Sandbox Code Playgroud)
现在我希望每个ele都被它重复freq并保存在一个新列表中。理想情况下,最好是repeat()从 numpy使用。
repeated = list(np.repeat(key, val) for key, val in sorted(combined.items())) # If a dict needs sorting
>>> print(repeated)
[1,1,1,1,1,2,2,2,2, ... ,4,4,5]
Run Code Online (Sandbox Code Playgroud)
但是,我想在不使用重复的情况下做到这一点。什么是进行的好方法?
一种使用方式collections.Counter:
d = {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}
list(Counter(d).elements())
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |