簡體   English   中英

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)

您實際上是在嘗試將列表轉換為整數。 這就是錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM