python 简介需要帮助查找单个字典值 (“model_year”) 的平均值

Intro to python need help finding average of a single dictionary value ("model_year")

提问人:Conner Kristian Amano-Lee 提问时间:10/25/2023 最后编辑:QiuConner Kristian Amano-Lee 更新时间:10/26/2023 访问量:28

问:

import csv #Informs Python that we want to use the csv module.

vehicleInventory = {}

with open('cars.csv', newline='') as csvfile:
    filereader = csv.DictReader(csvfile, delimiter = ',', quotechar = '"')
    counter = 0
    for row in filereader:
        counter += 1

        # TASK 1, copying rows in filereader into a dictionary
        vehicleInventory[counter] = row

vehicleInventory[100] = {"model_year": str(2001), "type":"Car", "make":"MINI", "model":"S", "transmission":"6-speed", "primary_color":"Red" }
vehicleInventory[101] = {"model_year": str(2020), "type":"Motorcycle", "make":"Yamaha", "model":"R6", "transmission":"6-speed", "primary_color":"black"}
vehicleInventory[102] = {"model_year": str(2020), "type":"SUV", "make":"Chevrolet", "model":"Suburban", "transmission":"Automatic", "primary_color":"Grey"}

#for key in vehicleInventory:
     #print("Vehicle " + str(key) + " information:")
     #print("MAKE " + vehicleInventory[key]["make"])
     #print("Year: " + vehicleInventory[key]["model_year"])
     #print("MODEL " + vehicleInventory[key]["model"])
     #print( "Color " + vehicleInventory[key]["primary_color"])

这是用于查找值的大部分代码,我需要找到模型年份的平均值。

from functools import reduce
  
def accumulate(x, y): 
    return x + y 
  
def dict_mean(d): 
    values_sum = reduce(accumulate, d.values()) 
    mean = values_sum / len(d) 
    return mean

for key in vehicleInventory:
    d = int(vehicleInventory[key]["model_year"])
    print (str("Mean:", dict_mean(d)))

我尝试了多种方法,这是最新的方法,但由于某种原因,它一直卡在值和上,而不是 int,而它通常不应该在乎。如果有更好的方法,请分享,因为我不知道这是否是远程工作。

python 字典 平均 键值

评论


答:

1赞 Maurizio Brini 10/26/2023 #1

这对我有用。 应该是字典列表(所以使用方括号)。您应该读取 csv 文件的每一行,并将其分配给相应的字典,您可以将其附加到列表中。vehicleInventoryvehicleInventory

vehicleInventory = []

#File read, dictionary assignment for each row

vehicleInventory.append({"model_year": str(2001), "type":"Car", "make":"MINI", "model":"S", "transmission":"6-speed", "primary_color":"Red" })
vehicleInventory.append({"model_year": str(2020), "type":"Motorcycle", "make":"Yamaha", "model":"R6", "transmission":"6-speed", "primary_color":"black"})
vehicleInventory.append({"model_year": str(2020), "type":"SUV", "make":"Chevrolet", "model":"Suburban", "transmission":"Automatic", "primary_color":"Grey"})


counter = 0
for element in vehicleInventory:
    counter += int(element["model_year"])

mean = counter/len(vehicleInventory)

print(mean)
#Returns 2013.6666666666667