Python 使用公式将字符串列表转换为整数
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)
您实际上是在尝试将列表转换为整数。这是错误的原因。
我可以用公式简单地将字符串转换为整数,例如:
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)
您实际上是在尝试将列表转换为整数。这是错误的原因。