Python'int'对象不可订阅

时间:2011-10-30 21:56:37

标签: python scriptable

我试图读取文件并确保每个值都是有序的。我不认为我正确地将字符串转换为整数。这是我的一些代码。我也在尝试使用旗帜。

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 :(得分:4)

你是对的 - 你用eval(xStr)[i]指示eval(xStr)是一个数组,因此可以下标。您可能想要的内容(因为您说要将字符串转换为int)只是int(xStr),以构成整行:

if int(xStr) < i:

答案 1 :(得分:1)

首先,你根本不读整个文件。试试这个:

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

但不确定,“每个值是按顺序”是什么意思,但使用eval()对于任何目的来说都是一个非常糟糕的主意。

答案 2 :(得分:0)

我想补充一点,因为你正在比较xstr [i]和i,除非你的第一个数字小于零,否则标志会改变,这意味着序列1 2 3 4 5会打印出“NO,the数字不符合“

答案 3 :(得分:0)

正如Chris指出的那样,int(s)是将字符串转换为整数的首选方法。 eval(s)过于宽泛,在评估来自不受信任来源的数据时可能存在安全风险。

此外,脚本中还有另一个错误。 * correct_order_flag *正在每次迭代时设置,因此具有错误顺序的一个条目可以通过正确顺序的后续条目进行掩码。因此,当发现错误的排序时,你应该摆脱循环。