I am new to python
I found topics on about counting frequency of numbers in a list. However, in my problem I want to get the frequency corresponding to a second consecutive list so that missing elements are assigned zero counts. My searched list:
Earthquake_Magnitude = [ 3.5 4.4 3.4 3.6 3.2 3.3 3.7 3. 3.1 4.3 3.9 3.2 3.1 3.2 3.6 3.1 4. 3.5 4.4 3. 3. 3.6 4.2 3.7 3.1 3.4 3.1 3.6 3.4 3. 4.1 3.4 4.2 3.4 3.9 3. 3.9 3. 3. 3.5 3.2 3.1]
My second list:
Magnitude_bins = [ 3. 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 4. 4.1 4.2 4.3 4.4]
Import groupby and define your lists with 2.9 added as a proof of the 0 as your predefined results are all in magnitude_bins.
from itertools import groupby
# Predefined lists from the question with the addition of 2.9 for proof of 0
earthquake_magnitude = [3.5, 4.4, 3.4, 3.6, 3.2, 3.3, 3.7, 3.0, 3.1, 4.3, 3.9,
3.2, 3.1, 3.2, 3.6, 3.1, 4.0, 3.5, 4.4, 3.0, 3.0, 3.6,
4.2, 3.7, 3.1, 3.4, 3.1, 3.6, 3.4, 3.0, 4.1, 3.4, 4.2,
3.4, 3.9, 3.0, 3.9, 3.0, 3.0, 3.5, 3.2, 3.1, 2.9]
magnitude_bins = [3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, 4.1,
4.2, 4.3, 4.4]
Now sort the list so that groupby can do its thing
earthquake_magnitude.sort()
Now we create a list of strings of "magnitude: count" if it is in magnitude_bins otherwise make the count = 0
output = [str(key) + ": " + str(len(list(group))) if key in magnitude_bins \
else str(key) + ": " + str(0) \
for key, group in groupby(earthquake_magnitude)]
Show the output
print(output)