I am using the latest version of python and pycharm professional edition. I am trying to figure out how to take an array like [15, 15, 15, 4, 4, 4, 4, 4, 4] and output [3, 15, 6, 4] where one number represents how many times a value appears in the array and the other number represents what the value was. In the example I provided there are 15 appears 3 times and 4 appears 6 times so the output is [3, 15, 6, 4]. I already have a method that counts the number of unique elements within an array (In the case of this example it would be 2) but I am unsure how I would go about storing both what the value is and how many times it appears. Any help would be appreciated.
CodePudding user response:
Simply, you can just convert the array list to a set
and then use the count
method.
lst=[15, 15, 15, 4, 4, 4, 4, 4, 4]
out=[[lst.count(i),i] for i in set(lst)]
print(out)
OUTPUT
[[6, 4], [3, 15]]
CodePudding user response:
This is a good case for a dictionary. The key would be your number the value would be the count. Scan through your list. You must have that code if you can count how many different numbers are in the list.
Test if the number exists in the dictionary. if yes increment the count. If not store 1 for the new key added.
CodePudding user response:
I'm not sure about built in methods but an algorithm to do this would look something like
counts = {}
for i in range(len(my_array)):
if my_array[i] in counts.keys():
counts[my_array[i]] = 1
else:
counts[my_array[i]] = 1
CodePudding user response:
In case you want to work with numpy
:
import numpy as np
l = [15, 15, 15, 4, 4, 4, 4, 4, 4]
np.vstack(np.unique(l, return_counts= True)[::-1]).ravel(order='F')
output:
array([ 6, 4, 3, 15])
Here, the order is by ascendant value of l