-->

How to convert strings with billion or million abb

2020-08-09 04:20发布

问题:

i have few string items which are the numbers with billion or million abbreviation in a list:

list = ["150M", "360M", "2.6B", "3.7B"]

I would like to use a syntax that could convert those string items into integers counted in thousands (e.g 150M > 150,000, 3.7B> 3,700,000 ), thanks

回答1:

You can use list comprehension with a dict mapping:

l = ["150M", "360M", "2.6B", "3.7B"]
m = {'K': 3, 'M': 6, 'B': 9, 'T': 12}
print([int(float(i[:-1]) * 10 ** m[i[-1]] / 1000) for i in l])

This outputs:

[150000, 360000, 2600000, 3700000]


回答2:

you should really show some attempt to try solve the problem yourself, but here is a simple example:

multipliers = {'K':1000, 'M':1000000, 'B':1000000000}

def string_to_int(string):
    if string[-1].isdigit(): # check if no suffix
        return int(string)
    mult = multipliers[string[-1]] # look up suffix to get multiplier
     # convert number to float, multiply by multiplier, then make int
    return int(float(string[:-1]) * mult)

testvals = ["150M", "360M", "2.6B", "3.7B"]

print(list(map(string_to_int, testvals)))


回答3:

Another solution, using re.sub:

import re

lst = ["150M", "360M", "2.6B", "3.7B"]
tbl = {'K':1, 'M':1_000, 'B':1_000_000}

new_lst = [int(i) for i in (re.sub(r'([\d\.]+)(K|M|B)', lambda v: str(int(float(v.groups()[0]) * tbl[v.groups()[1]])), i) for i in lst)]
print(new_lst)

Prints:

[150000, 360000, 2600000, 3700000]