我正在尝试读取 csv 文件并尝试编写以某种格式打印的逻辑。我已经做了如下,我想问你是否可以做得更好。 我的逻辑如下:
import csv, urllib2
url = 'http://winterolympicsmedals.com/medals.csv'
...
for country in countryList:
silver = len([item for item in aList if item[7]=='Silver' and item[4]==country])
gold = len([item for item in aList if item[7]=='Gold' and item[4]==country])
bronze = len([item for item in aList if item[7]=='Bronze' and item[4]==country])
result.append((country,gold,silver,bronze))
result
谢谢,非常感谢您的建议。 :)
最佳答案
您可以考虑使用计数器。
from collections import Counter, namedtuple
...
Result = namedtuple('Result', ['country','medal'])
aList = [Result(country=row[4],medal=row[7]) for row in cr]
medal_counts = Counter(alist)
然后根据您的需要对结果进行排序并打印出来。
这将给出(国家,奖章)的出现次数
,您应该能够轻松解析它以给出最终列表。
请注意,您可以像访问 dict
一样访问 Counter
:
swedish_bronze_count = medal_counts[("SWE", "Bronze")]
关于python - 使用列表和 csv 文件进行高效计数/排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37802675/