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)
你的步骤应该是:
这可以通过以下方式实现:
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)
| 归档时间: |
|
| 查看次数: |
1151 次 |
| 最近记录: |