简体   繁体   中英

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

If I have a list of strings, I then won't be able to put in the 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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