Python - 使用创建的列表作为参数

时间:2015-06-15 05:24:44

标签: python list loops if-statement compare

当我运行我的代码时,它会告诉我:类型错误:无法解决的类型:str()<浮动()。我无法弄清楚为什么它不会让我比较这两个数字。我正在使用的列表已经定义,其中的数字已被重新定义为浮点数,所以我不确定还能做什么。有什么建议吗?

    def countGasGuzzlers(list1, list2):   
        total = 0
        CCount = 0
        HCount = 0
        for line in list1:
            if num < 22.0:
                total = total + 1
                CCount = CCount + 1
        for line in list2:
            if num < 27.0:
                total = total + 1
                Hcount = Hcount = 1
        print('City Gas Guzzlers: ',CCount)
        print('Highway Gas Guzzlers: ',HCount)
        print('Total Gas Guzzlers: ',total)

这是我的清单定义。我很确定这很好,但也许这里也有一些错误?

     CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
    for line in CityFile:
            CityData = CityFile.readlines()
            for num in CityData:
                numCityData = float(num)
                CityList = numCityData
    HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
    for line in HwyFile:
            HwyData = HwyFile.readlines()
            for num in HwyData:
                    numHwyData = float(num)
                    HwyList = numHwyData

1 个答案:

答案 0 :(得分:0)

我认为您错误地引用了num而不是line这是for循环中的计数器变量,您需要使用num作为计数器变量,或在line条件中使用if

def countGasGuzzlers(list1, list2):   
    total = 0
    CCount = 0
    HCount = 0
    for line in list1:
        if float(line) < 22.0:
            total = total + 1
            CCount = CCount + 1
    for line in list2:
        if float(line) < 27.0:
            total = total + 1
            Hcount = Hcount = 1
    print('City Gas Guzzlers: ',CCount)
    print('Highway Gas Guzzlers: ',HCount)
    print('Total Gas Guzzlers: ',total)

我看到的另一个问题是您创建列表的方式。问题是你要将文件中的每个num转换为float,然后将其直接存储在list变量中,这会导致list变量实际存储浮点值而不是列表,你需要将每个值附加到列表中,而不是执行{ {1}}

代码看起来像 -

list = num

请确保在此代码之前将CityList和HwyList初始化为列表。如下 -

CityFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_city','r')
for line in CityFile:
        CityData = CityFile.readlines()
        for num in CityData:
            numCityData = float(num)
            CityList.append(numCityData)
HwyFile = open('F://SSC/Spring 2015/CSC 110/PythonCode/Chapter 8/HW 4/carModelData_hwy','r')
for line in HwyFile:
        HwyData = HwyFile.readlines()
        for num in HwyData:
                numHwyData = float(num)
                HwyList.append(numHwyData)