我正在嘗試更改串列的內容,更改每個-127for a1和-128for a 0。但是,我很難找到為什么我的代碼沒有按預期更改數字甚至無法識別它們:
my_file = open("log.txt", "r")
content = my_file.read()
my_file.close()
clean_contnet = content.split("\n")
for idx, x in enumerate(clean_contnet):
if x == -127 or x == -128:
if x == -127:
clean_contnet[idx] = 1
else:
clean_contnet[idx] = 0
else:
print("no -127 or -128 detected")
print(clean_contnet)
的(縮短)內容'log.txt'如下
0 -127 1 -128 0 -127 1 -128 0 -127 1
uj5u.com熱心網友回復:
clean_contnet是一個字串串列,而不是整數。你應該x = int(x)在檢查它的值之前做。
uj5u.com熱心網友回復:
您永遠不會將讀取的字串資料轉換為整數 - 將字串與數字進行比較永遠不會導致True陳述句。
改變:
# convert read in numbers to string - will crash if non numbers inside
clean_content = [int(part) for part in content.split("\n") if part]
或比較與字串:
if x in ("-127","-128"):
clean_content[idx] = 1 if x == "-127" else 0
這使用三元運算式 - 請參閱Python 是否有三元條件運算子?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/385023.html
