将字符串更改为整数

Ann*_*a K 1 python regex python-2.7

我快疯了,找不到正确的解决方案:(

我该如何解决这些问题。我有一个循环,我可以得到不同的类型,例如:

empty string
10
10K
2.3K
2.34K
2M
2.2M
2.23M
Run Code Online (Sandbox Code Playgroud)

我需要将它们更改为数字:

0
10
10000
2300
2340
2000000
2200000
2230000
Run Code Online (Sandbox Code Playgroud)

Sov*_*iut 5

你的步骤应该是:

  • 检查字符串是否为空
    • 返回0
  • 检查字符串是否以 K 或 M 结尾
    • 如果是,则将该字符从末尾去掉,存储起来供以后使用
    • 乘以适当的系数(K = 1000 或 M = 1000000)

这可以通过以下方式实现:

def convert(value):
    if value:
        # determine multiplier
        multiplier = 1
        if value.endswith('K'):
            multiplier = 1000
            value = value[0:len(value)-1] # strip multiplier character
        elif value.endswith('M'):
            multiplier = 1000000
            value = value[0:len(value)-1] # strip multiplier character

        # convert value to float, multiply, then convert the result to int
        return int(float(value) * multiplier)

    else:
        return 0

values = [
    '',
    '10',
    '10K',
    '2.3K',
    '2.34K',
    '2M',
    '2.2M',
    '2.23M',
]

# use a list comprehension to call the function on all values
numbers = [convert(value) for value in values]

print numbers
Run Code Online (Sandbox Code Playgroud)

这应该返回

[0, 10, 10000, 2300, 2340, 2000000, 2200000, 2230000]
Run Code Online (Sandbox Code Playgroud)