python - 使用列表和 csv 文件进行高效计数/排序

标签 python list

我正在尝试读取 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/

相关文章:

arrays - 有效地迭代 Haskell 中多个数组/列表的前缀

python - 保留 python 字典顺序 - (python dict 的延续)

python - 使用 PyScripter 执行带有参数的 python 文件

python - 属性错误 : 'DiGraph' object has no attribute '_node'

python - 为什么没有打印任何行并且估计系数为 NaN?

python - 根据索引将Python列表拆分为多个列表

r - 折叠一个数据框列表并与 R 中的另一个数据框列表组合

将 poll() 应用于 LinkedList 时发生 Java 错误

python - TabPy - 无效的文件路径或缓冲区对象类型

python - 树莓派、Python、检测操作系统