csv 我怎样才能得到数组列表中一列的最小值并将其添加到字典中?

zujrkrfu  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(177)

我正在编写一段代码,它可以从python打开csv文件,并使用它提供的信息。这个文件取自LeMans竞赛,包含电路扇区时间等内容。我使用的文件如下:CSV FILE IMAGE(每一列都属于某个信息,同一个团队在行中重复多次,但次数或其他信息不同)
目前我已经做了这个代码,但当我想保存每个团队的最佳时间,它保存最后的或那些不是。
代码:

def csv_reader ():
    correct = False
    while (not correct):
        try:
            filename=input("FileName.csv: ")
            f=open(filename, "r")
            csv_list = f.readlines()
            correct = True    
        except IOError:
            print("ERROR")
    f.close()
    return csv_list

def csv_data (csv_list):
    dictionary_1={}
    for line in csv_list: 
        data=line.split(';')
        team=data[0] 
        S1=(data[26])
        if team in dictionary_1:
            if dictionary_1[team][0]>S1:
                dictionary_1[team][0]=S1
        else:
            dictionary_1[team]=[0]
            dictionary_1[team][0]=S1
    return dictionary_1

csv_list = csv_reader()
del csv_list[0]

print (csv_data(csv_list))

我希望代码读取列中的每一行,并保存(在本例中)字典中每个团队的最小值。
谢谢!

3okqufwl

3okqufwl1#

你提供的图片与你的代码不匹配(...... vs field 26)。也就是说,调整一下,它看起来像预期的那样工作。稍微调整了一下代码:

def csv_data(csv_list, circuit_sect=26):
    dictionary_1 = {}
    for line in csv_list:
        data = line.split(';')
        team = data[0]
        S1 = float(data[circuit_sect].strip())
        if team not in dictionary_1 or dictionary_1[team] > S1:
            dictionary_1[team] = S1
    return dictionary_1

csv_list = [
        "1;...;36.067\n",
        "1;...;36.879\n",
        "10;...;37.768\n",
        "10;...;34.998\n"
]
print(csv_data(csv_list, 2))

并且输出:

{'1': 36.067, '10': 34.998}

相关问题