比较表格中的数字:python 中的 12,3K 和 1,84M

Compare numbers in form: 12,3K , 1,84M in python

需要比较如下数字:12,3K、1,84M 等 例如:

a = 12,3K 
b = 1,84M
if b > a :
    print b 

您需要为其使用替换:

a = ("12,3K", "1,84M")
numbers = {"K": 1000, "M": 1000000}

result = []

for value in a:
    if value:
        i = value[-1]
        value = float(value[:-1].replace(',', '.')) * numbers[i]
        result.append(int(value))

print max(result)

您可以在词典中添加更多的数字,您会得到更多的结果。

我会推荐一个函数来将 ab 转换成相应的数字(我也会制作 ab 字符串:

def convert(num):
    return num.replace(',','').replace('K','000').replace('M','000000')

a = '12,3K'
b = '1,84M'
if convert(b) > convert(a) :
    print b

如果您的值是字符串,那么 re 模块可以很容易地用 '' 替换逗号,用 3 个或 6 个零替换 K 或 M。然后包裹在 int() 中并进行比较。您在哪里/如何获得要比较的值?