首页 > 解决方案 > Create new array from a defined array

问题描述

If I have an array, a = [1,2,3,4,2,1], how can I create another array, which shows the number of times each number in array a has been repeated, for example from array a then the new array would be b = [2,2,1,1]? Is this possible using a command in the NumPy library?

标签: pythonarraysnumpyrepeat

解决方案


我敢肯定有很多方法可以做到这一点。这是一个:

a = [1,2,3,4,2,1]

count = {}
for item in a: 
    count[item] = count.get(item, 0) + 1

[v for k,v in count.items()]

结果:

[2, 2, 1, 1]

推荐阅读