简体   繁体   English

python elementtree-得到平均

[英]python elementtree - getting average

Using element tree in python, I want to get an average value. 我想在python中使用元素树,以获取平均值。

Below is my data 以下是我的数据

Order A has a quantity of 12,10,and 5.. total is 27
Order B has a quantity of 9 and 40... total is 49
Order C has a quantity of 10,35, and 15.. total is 60  

When you total them then divide by 3, I should be getting 45.33. 当您总计它们然后除以3时,我应该得到45.33。 But on my code below, I'm getting 20. :( I'm extracting the above data from an XML file. Can you please help me identify the problem on my code. Thank you. 但是在下面的代码中,我得到20::(我正在从XML文件中提取上述数据。请您帮我确定代码中的问题。谢谢。

import xml.etree.ElementTree as ET
root = ET.ElementTree(file="nwind_medium.xml")

orders = root.findall("./orders")
for order in orders:
    orderdetails = order.findall("./orderdetails")
    total = 0
    for detail in orderdetails:
        quantity = detail.findall("./quantity")
        total += float(quantity[0].text)
numberOrders = len(orders)

print "The average number of itmes in order is", round((total / numberOrders),2)

Here's the whole XML file (updated) - - - Vins et alcools Chevalier VINET - - 72 Mozzarella di Giovanni 34.8 5 - 14 Formaggi Fortini srl - - 11 Queso Cabrales 14 12 - 5 Cooperativa de Quesos 'Las Cabras' - - 42 Singaporean Hokkien Fried Mee 9.8 10 - 20 Leka Trading - - Toms Spezialitaten TOMSP - - 14 Tofus 18.6 9 - 6 Mayumi's - - 51 Manjimup Dried Apples 42.4 40 - 24 G'day, Mate - - Hanari Carnes HANAR - - 65 Louisiana Fiery Hot Pepper Sauce 16.8 15 - 2 New Orleans Cajun Delights - - 41 Jack's New England Clam Chowder 7.7 10 - 19 New England Seafood Cannery - - 51 Manjimup Dried Apples 42.4 35 - 24 G'day, Mate 这是整个XML文件(已更新)---Vins et alcools Chevalier VINET--72 Mozzarella di Giovanni 34.8 5-14 Formaggi Fortini srl--11 Queso Cabrales 14 12-5 Cooperativa de Quesos'Las Cabras'--42新加坡福建人Fried Mee 9.8 10-20 Leka Trading--Toms Spezialitaten TOMSP--14豆腐18.6 9-6 Mayumi's--51 Manjimup苹果干42.4 40-24 G'day,伴侣--Hanari Carnes HANAR--65路易斯安那州火辣辣椒酱16.8 15-2新奥尔良Cajun美食--41杰克新英格兰蛤C浓汤7.7 10-19新英格兰海鲜罐头厂--51 Manjimup苹果干42.4 35-24天,伴侣

You are resetting total on each iteration through an order. 您正在通过订单重置每次迭代的总数。 If you need total of all orders move 如果您需要所有订单总计

total = 0

before the outer loop. 在外循环之前。

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

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