我有一个简单的数字字典及其各自的频率,是我结合两个列表制作的:
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}
现在我想要每个 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]
但是,我想不使用重复来执行此操作。什么是继续的好方法?
最佳答案
使用collections.Counter
的一种方法:
d = {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}
list(Counter(d).elements())
输出:
[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]
关于python - 在字典中按其键值重复每个成员而不使用 np.repeat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59747545/