[英]How to convert SI units to number using python
I want to convert the numbers which come with the letters and convert it based on the value each letter specifies.我想转换字母附带的数字,并根据每个字母指定的值进行转换。 Like a number 1M should be read as 1000000 and a number 1K should be read as 1000. Is there some simple method to get this done?
就像一个数字 1M 应该读为 1000000,一个数字 1K 应该读为 1000。有什么简单的方法可以做到这一点?
Convert the last character to a value, eg M -> 1000000, k -> 1000. Multipy with the value and add some code for possible parse errors.将最后一个字符转换为一个值,例如 M -> 1000000, k -> 1000。乘以该值并为可能的解析错误添加一些代码。
(I deliberately did not add code here to let you give it a try). (这里特意没有加代码让大家试一试)。
A trivial approach would be to use a dictionary to store the number of zeros each conversion would use:一种简单的方法是使用字典来存储每次转换将使用的零数:
>>> number = {
... 'K': 3,
... 'M': 6
... }
>>>
>>> var = '5M'
>>> int(var[0] + ('0' * number[var[1]]))
5000000
>>> var = '2K'
>>> int(var[0] + ('0' * number[var[1]]))
2000
>>>
This solution may or may not be scalable depending on the size and complexity of your project.根据项目的规模和复杂性,此解决方案可能具有可扩展性,也可能不具有可扩展性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.