Python 'int' 对象不可订阅

0 投票
4 回答
4011 浏览
提问于 2025-04-17 05:18

我正在尝试读取一个文件,并确保里面的每个数值都是按顺序排列的。我觉得我没有正确地把字符串转换成整数。以下是我写的一部分代码。我还在尝试使用标志。

fileName = input("What file name? ")
infile = open(fileName,'r')
correct_order_flag = False
i = 0
line = infile.readline()
while line !="": 
    for xStr in line.split(" "):
        if eval(xStr) [i] < i:
            correct_order_flag = True
        else:
            correct_order_flag = False
    i = i+1
if correct_order_flag:
    print("Yes, the numbers were in order")
else:
    print("No, the numbers were not in order")
count = i - 1
print("There were", count, "numbers.")

4 个回答

0

正如Chris所说,使用int(s)是把字符串转换成整数的推荐方法。eval(s)的功能太广泛了,当你处理不可信的数据时,使用它可能会带来安全风险。

另外,脚本中还有一个错误。*correct_order_flag*在每次循环时都会被设置,所以如果有一个顺序不正确的条目,后面一个顺序正确的条目就会掩盖它。因此,当发现顺序不正确时,你应该立即跳出循环。

1

首先,你根本不需要一次性读取整个文件。试试这个:

with open(fileName) as f:
    for line in f:
        # here goes your code

不过我不太明白你说的“每个值都是有序的”是什么意思,但使用 eval() 是个非常糟糕的主意,不管是什么情况。

4

你说得对,使用 eval(xStr)[i] 这段代码是在告诉程序 eval(xStr) 是一个数组,所以可以用下标来访问它的元素。不过,看起来你真正想要的(因为你说想把字符串转换成整数)其实是直接用 int(xStr)。这样整行代码就变成了:

if int(xStr) < i:

撰写回答