我有一个.csv文件,在Excel中打开时如下所示:
我的代码:
myfile = open("/Users/it/Desktop/Python/In-Class Programs/countries.csv", "rb")
countries = []
for item in myfile:
a = item.split(",")
countries.append(a)
hdi_list = []
for acountry in countries:
hdi = acountry[3]
try:
hdi_list.append(float(hdi))
except:
pass
average = round(sum(hdi_list)/len(hdi_list), 2)
maxNumber = round(max(hdi_list), 2)
minNumber = round(min(hdi_list), 2)
这个代码工作得很好,但是,当我找到max、min或avg时,我需要获取相应的国家名称并将其打印出来。在
如何更改我的代码以获取最小值、最大值、平均值的国家名称?在
下面的方法与您的实现非常接近,我认为它可能有用。但是,如果您开始处理更大或更复杂的csv文件,您应该查看类似于csv.reader或“熊猫”(如前所述)。它们在处理复杂的.csv数据时更加健壮和高效。你也可以使用“xlrd”包在Excel中工作。在
在我看来,引用国家名称和它们各自的值的最简单的解决方案是组合您的“for循环”。不要在数据中循环两次(在两个单独的“for循环”中)和创建两个单独的列表,而是使用一个“for循环”并创建一个包含相关数据的字典(即“country name”、“hdi”)。您也可以创建元组(如前所述),但我认为字典更显式。在
请注意,如果多个国家的最小值/最大值相等,则此方法将返回多个国家。在
如果您不想创建单独的列表(比如您当前的实现),可以考虑使用zip()连接列表(按索引),其中
^{pr2}$例如:
把类似的逻辑应用到最小值和平均值。这种方法有效,但不太明确,更难维护。在
使用下面的}应该分别显示最大值、最小值和平均值。请注意,下面的数据与您的save for country不匹配。在
pandas
模块,[4]
,[5]
,和{假设
^{pr2}$Liechtenstein
和Germany
都有最大值:同样的逻辑也适用于最小值。在
不要直接将值放入列表中,而是使用元组,如下所示:
然后您可以使用此选项:
^{pr2}$相关问题 更多 >
编程相关推荐