Python 简介:如何查找单个字典值(“model_year”)的平均值

问题描述 投票:0回答:1
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)))

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

python dictionary key average key-value
1个回答
1
投票

这对我有用。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.