Python - 将后缀面额转换为值
给定带有面额后缀的字符串列表,任务是编写一个Python程序将字符串转换为其实际值,替换面额实际值。
Input : test_list = [“25Cr”, “7M”, “24B”, “9L”, “2Tr”, “17K”]
Output : [250000000.0, 7000000.0, 24000000000.0, 900000.0, 2000000000000.0, 17000.0]
Explanation : Suffix replaced as per Symbol notations with numerical figure.
Input : test_list = [“25Cr”, “7M”, “24B”]
Output : [250000000.0, 7000000.0, 24000000000.0]
Explanation : Suffix replaced as per Symbol notations with numerical figure.
方法:使用float() +字典+循环
在此,我们用其原始值构建所有面额的字典,然后将值转换为浮点数并与面额的实际值进行乘法运算。
Python3
# Python3 code to demonstrate working of
# Convert Suffix denomination to Values
# Using float() + dictionary + loop
# initializing list
test_list = ["25Cr", "7M", "24B", "9L", "2Tr", "17K"]
# printing original list
print("The original list is : " + str(test_list))
# initializing values dictionary
val_dict = {"M": 1000000, "B": 1000000000, "Cr": 10000000,
"L": 100000, "K": 1000, "Tr": 1000000000000}
res = []
for ele in test_list:
for key in val_dict:
if key in ele:
# conversion of dictionary keys to values
val = float(ele.replace(key, "")) * val_dict[key]
res.append(val)
# printing result
print("The resolved dictionary values : " + str(res))
输出:
The original list is : [’25Cr’, ‘7M’, ’24B’, ‘9L’, ‘2Tr’, ’17K’]
The resolved dictionary values : [250000000.0, 7000000.0, 24000000000.0, 900000.0, 2000000000000.0, 17000.0]