我有一个带有值的嵌套列表:
list = [
...
['Country1', 142.8576737907048, 207.69725105029553, 21.613192419863577, 15.129178465784218],
['Country2', 109.33326343550823, 155.6847323746669, 15.450489646386226, 14.131554442715336],
['Country3', 99.23033109735835, 115.37122637190915, 5.380298424850267, 5.422030104456135],
...]
Run Code Online (Sandbox Code Playgroud)
我想按照数量级计算第二个索引/列中的值,从最低数量级开始并以最大数量结束...例如
99.23033109735835 = 10 <= x < 100
142.8576737907048 = 100 <= x < 1000
9432 = 1000 <= x < 10000
Run Code Online (Sandbox Code Playgroud)
目的是输出一个简单的char(#)计数,表示每个类别中有多少个索引值,例如
10 <= x < 100: ###
100 <= x < 1000: #########
Run Code Online (Sandbox Code Playgroud)
我开始抓取索引的值max()和min()值来自动计算最大和较小的量级类别,但我不确定如何将列中的每个值与一个数量级关联...如果有人可以指出我在正确的方向或给我一些想法,我将非常感激.
Use*_*ess 17
此函数会将您的double变为整数数量级:
>>> def magnitude(x):
... return int(math.log10(x))
...
>>> magnitude(99.23)
1
>>> magnitude(9432)
3
Run Code Online (Sandbox Code Playgroud)
(所以10 ** magnitude(x) <= x <= 10 ** (1 + magnitude(x))对所有人来说x).
只需使用幅度作为键,并计算每个键的出现次数. defaultdict在这里可能会有帮助.
请注意,此幅度仅适用于10的正幂(因为int(double)截断向零舍入).
使用
def magnitude(x):
return int(math.floor(math.log10(x)))
Run Code Online (Sandbox Code Playgroud)
相反,如果这对您的用例很重要.(感谢larsmans指出这一点).
将“无用”答案扩展到所有实数,您可以使用:
import math
def magnitude (value):
if (value == 0): return 0
return int(math.floor(math.log10(abs(value))))
Run Code Online (Sandbox Code Playgroud)
测试用例:
In [123]: magnitude(0)
Out[123]: 0
In [124]: magnitude(0.1)
Out[124]: -1
In [125]: magnitude(0.02)
Out[125]: -2
In [126]: magnitude(150)
Out[126]: 2
In [127]: magnitude(-5280)
Out[127]: 3
Run Code Online (Sandbox Code Playgroud)