简体   繁体   English

如何使用python将SI单位转换为数字

[英]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.

相关问题 在 Python 中使用工程符号(带有 SI 前缀)将浮点数转换为字符串 - Convert float number to string with engineering notation (with SI prefix) in Python 如何在不使用python循环的情况下检测和转换列值的单位? - How to detect and convert units of column values without using python loop? 将python中的单位转换为非人类可读格式 - Convert number with units in python to NON human readable format Python 在 SI 单位前缀之间转换的库 - Python library to convert between SI unit prefixes 将多个单位转换为 TB,并使用 Python 进行计算 - Convert several units to TB as well as perform calculation using Python 如何使用 SI 前缀(micro、milli、Mega、Giga 等)格式化数字? - How do I format a number using SI prefix (micro, milli, Mega, Giga, etc)? 使用Keras时如何更改图层中的单位数? - How do you change the number of units in a layer when using Keras? Python 品脱单位如何使用货币单位? - How are currency units used with Python Pint units? 将单位表示法(100kb,32MB)的大小表示法转换为Python中的字节数 - Convert size notation with units (100kb, 32MB) to number of bytes in Python python可靠地将任何带有单位的字符串转换为float - python robustly convert any string with units to float
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM