首页 > 解决方案 > 尝试设置新的最大值时出错

问题描述

我现在的程序必须从我已经开始工作的 CSV 文本文件中获取数据,但是当我尝试将最大值设置为距离 [计数器] 时,我收到一个错误,其中指出:

类型错误:“str”和“float”的实例之间不支持“>”

我理解这一点,但我正在努力让它发挥作用。

forename = [""] * 100
surname = [""] * 100
distance = [0.0] * 100


# Gets the members details from the file

#strip the file by /n to get seperate lines

# split it by commas to get each value in each line

def get_members_info():
    counter = 0
    with open("members.txt",'r') as readfile:
        line = readfile.readline().rstrip('/n')
        while line:
            items = line.split(",")
            forename[counter] = items[0]
            surname[counter] = items[1]
            distance[counter] = items[2]

            line = readfile.readline().rstrip('/n')
            counter +=1
    return forename, surname, distance
#
def print_max_distance(forename, surname, distance):
    maximum = 0.0
    print (distance[0])
    for counter in range (1, len(distance)):
        if distance[counter] > maximum:
            maxs = distance[counter]
            print (maxs)
    print (maxs)

#
get_members_info()
print_max_distance(forename, surname, distance)

标签: pythonpython-3.x

解决方案


line是一个字符串,所以当你拆分它时,你会得到一个字符串列表。然后,您尝试将这些字符串与失败的浮点数进行比较。

如果您可以保证距离始终是一个数字,那么您可以简单地替换distance[counter] = items[2]distance[counter] = float(items[2])


推荐阅读