简体   繁体   English

遍历CSV文件

[英]Iterating over a csv file

I have to produce a function that will return a tuple containing the maximum temperature in the country and a list of the cities in which that temperature has been recorded. 我必须生成一个函数,该函数将返回一个元组,其中包含该国家/地区的最高温度以及已记录该温度的城市列表。 The data was input as a CSV file in the format: 数据以CSV文件格式输入:

Month, Jan, Feb, March....etc. 

So far I have managed to get the maximum temperature but when it tries to find the cities in which that temperature was found, it comes up as an empty list. 到目前为止,我已经设法获得了最高温度,但是当它试图找到发现该温度的城市时,它会作为一个空列表出现。

def hottest_city(csv_filename):
    import csv
    file = open(csv_filename)
    header = next(file)
    data = csv.reader(file)
    city_maxlist = []
    for line in data:
        maxtemp = 0.0
        for temp in line[1:]:
            if float(temp >= maxtemp:
                maxtemp = float(temp)
        city_maxlist.append([maxtemp, line[0])
    maxtempcity = 0.0
    for city in city_maxlist:
        if city[0] >= maxtempcity:
            maxtempcity = city[0]
    citylist = []
    for line in data:
        for temp in line:
            if temp == maxtempcity:
                citylist.append(line[0])
    return (maxtempcity, citylist)

Your main problem is that "data" is an iterator, so you can iterate over it only once (your second loop over data does not loop at all). 您的主要问题是“数据”是一个迭代器,因此您只能对其进行一次迭代(您对数据的第二次循环根本不会循环)。

data = list(csv.reader(file))

should help. 应该有所帮助。 Then as Hans Then noticed, you did not provide the code you execute, so I let you correct your tests in the second loop over data. 然后,就像Hans Then注意到的那样,您没有提供执行的代码,因此我让您在数据的第二个循环中更正测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM