python for循环无法识别列表中的int



我正在尝试更改列表的内容,将每个-127更改为1,将-128更改为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

clean_contnet是字符串列表,而不是int。您应该先执行x = int(x),然后再检查其值。

您永远不会将读入的字符串数据转换为整数-将字符串与数字进行比较永远不会产生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是否有三元条件运算符?

最新更新