简体   繁体   English

Python使用公式将字符串列表转换为整数

[英]Python convert a list of string to integer with a formula

I can simply convert a string to integer with a formula, for example:我可以简单地使用公式将字符串转换为整数,例如:

lines = '0x61'
(int(lines ,16)*2+128+100)*0.002

This outputs: 0.844这输出:0.844

If I have a list of strings, I then won't be able to put in the int() .如果我有一个字符串列表,那么我将无法放入int()

lines = ['0x83',
'0x00',
'0x7D',
'0x00',
'0x90']
(int(lines ,16)*2+128+100)*0.002

This output an error: int() can't convert non-string with explicit base此输出错误: int() can't convert non-string with explicit base

How can I solve this problem?我怎么解决这个问题?

You need to loop over the entries, or put it in a list comprehension:您需要遍历条目,或将其放入列表理解中:

>>> 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]

If it was me I'd probably make a little function to keep it tidy:如果是我,我可能会做一个小功能来保持整洁:

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]

You'd want to loop over a list, for example using a list comprehension:你想循环一个列表,例如使用列表理解:

list_of_strings = ['0x83', '0x00', '0x7D', '0x00', '0x90']
[(int(item,16)*2+128+100)*0.002 for item in list_of_strings]

Outputs:输出:

[0.98, 0.456, 0.9560000000000001, 0.456, 1.032]

You need to iterate over the elements in the list.您需要遍历列表中的元素。

str1 = ['0x83',
'0x00',
'0x7D',
'0x00',
'0x90']
for str2 in str1:
    integer=(int(str2,16)*2+128+100)*0.002
    print(integer)

You are literally trying to convert a list to an integer.您实际上是在尝试将列表转换为整数。 This is the cause of the error.这就是错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM