我需要列印 XML 資料中所有高于平均值的值。我想出了如何解決平均值,但我無法列印所有高于平均值的值。這是代碼,公式在 more_than_average 函式中
import xml.etree.cElementTree as ET
def load_data(fpath="properties.xml"):
tree = ET.parse(fpath)
root = tree.getroot()
prop_list = []
for child in root:
data = child.attrib.copy()
data['netIncome'] = float(child.text)
data["id"] = data["id"]
data['cost'] = float(data['cost'])
data['downPayment'] = float(data['downPayment'])
data['state'] = data['state']
data['percentage'] = float(data['percentage'])
prop_list.append(data)
return prop_list
def more_average_income(prop_list):
value = 0
for i in prop_list:
value = i['netIncome']
average = {round(value / len(prop_list), 2)}
more_aver_inc = (value > average)
print(more_aver_inc)
這是正在匯入的資料示例
<properties>
<property id="H00001" cost="106000" downPayment="24380" state="NM" percentage="0.12">2925.6</property>
<property id="H00002" cost="125000" downPayment="30000" state="AZ" percentage="0.15">4500</property>
<property id="H00003" cost="119000" downPayment="24990" state="NH" percentage="0.13">3248.7</property>
<property id="H00004" cost="124000" downPayment="31000" state="MI" percentage="0.19">5890</property>
<property id="H00005" cost="143000" downPayment="34320" state="CZ" percentage="0.11">3775.2</property>
<property id="H00006" cost="139000" downPayment="30580" state="VI" percentage="0.12">3669.6</property>
<property id="H00007" cost="132000" downPayment="26400" state="ND" percentage="0.19">5016</property>
<property id="H00008" cost="134000" downPayment="26800" state="CZ" percentage="0.17">4556</property>
<property id="H00009" cost="143000" downPayment="34320" state="PA" percentage="0.14">4804.8</property>
<property id="H00010" cost="123000" downPayment="25830" state="IN" percentage="0.2">5166</property>
<property id="H00011" cost="116000" downPayment="24360" state="IL" percentage="0.09">2192.4</property>
<property id="H00012" cost="150000" downPayment="36000" state="OR" percentage="0.11">3960</property>
<property id="H00013" cost="117000" downPayment="23400" state="VI" percentage="0.19">4446</property>
<property id="H00014" cost="116000" downPayment="26680" state="SC" percentage="0.16">4268.8</property>
</properties>
我不斷收到此錯誤
Traceback (most recent call last):
File "/Users/school/VisualStudio/01.LESSON/properties.py", line 77, in <module>
funct(data)
File "/Users/school/VisualStudio/01.LESSON/properties.py", line 59, in more_average_income
more_aver_inc = (value > average)
TypeError: '>' not supported between instances of 'float' and 'set'
uj5u.com熱心網友回復:
平均值是一個集合()
通過用括號括起您的值,您正在創建一個包含一個值的集合。Python 無法比較 float 和 set,這就是它拋出錯誤的原因。
average = round(value / len(prop_list), 2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/427382.html
