[英]Python convert a list of string to integer with a formula
我可以简单地使用公式将字符串转换为整数,例如:
lines = '0x61'
(int(lines ,16)*2+128+100)*0.002
这输出:0.844
如果我有一个字符串列表,那么我将无法放入int()
。
lines = ['0x83',
'0x00',
'0x7D',
'0x00',
'0x90']
(int(lines ,16)*2+128+100)*0.002
此输出错误: int() can't convert non-string with explicit base
我怎么解决这个问题?
您需要遍历条目,或将其放入列表理解中:
>>> strings = ['0x83', '0x00', '0x7D', '0x00', '0x90']
>>> [(int(s, 16)*2+128+100)*0.002 for s in strings]
[0.98, 0.456, 0.9560000000000001, 0.456, 1.032]
如果是我,我可能会做一个小功能来保持整洁:
def transform(s: str) -> float:
"""Transform strings to floats."""
return (int(s, 16)*2+128+100)*0.002
strings = ['0x83', '0x00', '0x7D', '0x00', '0x90']
[transform(s) for s in strings]
你想循环一个列表,例如使用列表理解:
list_of_strings = ['0x83', '0x00', '0x7D', '0x00', '0x90']
[(int(item,16)*2+128+100)*0.002 for item in list_of_strings]
输出:
[0.98, 0.456, 0.9560000000000001, 0.456, 1.032]
您需要遍历列表中的元素。
str1 = ['0x83',
'0x00',
'0x7D',
'0x00',
'0x90']
for str2 in str1:
integer=(int(str2,16)*2+128+100)*0.002
print(integer)
您实际上是在尝试将列表转换为整数。 这就是错误的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.