我是python的新手
我找到了关于计算列表中数字频率的主题。但是,在我的问题中,我希望得到与第二个连续列表相对应的频率,以便为缺失的元素分配零计数。我的搜索列表:
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]
我的第二个清单:
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]
导入groupby并定义您的列表,添加2.9作为0的证明,因为您的预定义结果都在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]
现在对列表进行排序,以便groupby可以完成它的工作
earthquake_magnitude.sort()
现在我们创建一个“magnitude:count”字符串列表,如果它在magnitude_bins中,否则使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)]
显示输出
print(output)
我们来定义你的清单:
>>> 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]
>>> 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]
现在,让我们在Earthquake_Magnitude
中获取一些条目,忽略不在Magnitude_bins
中的任何条目:
>>> from collections import Counter
>>> c = Counter(x for x in Earthquake_Magnitude if x in set(Magnitude_bins))
>>> c
Counter({3.0: 7, 3.1: 6, 3.4: 5, 3.2: 4, 3.6: 4, 3.9: 3, 3.5: 3, 4.4: 2, 4.2: 2, 3.7: 2, 3.3: 1, 4.1: 1, 4.3: 1, 4.0: 1})
正如你所看到的3.0
在Earthquake_Magnitude
发生了7次
我认为你最好创建一个“字典”,这是一个从键到值的查找表。在这种情况下,你的“密钥”(你在字典中查询它的东西)将是地震的大小,而“值”(查询中出现的字典)将是地震的数量那么大。
所以,你可以尝试:
from collections import defaultdict
freq = defaultdict(int)
for thisEvent in Earthquake_Magnitude:
freq[thisEvent] += 1
for thisBin in Magnitude_bins:
print(str(thisBin) + " has frequency " + str(freq[thisBin]))
在这种情况下,defaultdict
是一个具有默认值的字典,以便使您的所有起始频率为0。