Python读取CSV统计指定列频次后如何按字母顺序排序输出
解决方法
你现有的统计逻辑完全正确,只需要修改最后遍历输出的部分即可实现按字母升序排序的效果。
普通字典在Python 3.7以前是完全无序的,3.7及以后版本也只会保留插入顺序,不会自动按键排序,所以你只需要在输出前对字典的键做一次排序即可。
修改后的完整代码
import csv with open("FILENAME", newline="", encoding="iso-8859-1") as csvfile: reader = csv.reader(csvfile, delimiter=";") next(reader) species_count ={} for row in reader: species = row[12] species_count[species] = species_count.get(species,0)+1 # 仅修改下方遍历逻辑,对字典的键做升序排序后再遍历 for species in sorted(species_count): print(f"{species}: {species_count[species]}")
扩展可选写法
如果后续你有按出现频次排序的需求,可以调整sorted的排序规则:
# 按字母升序排序,和上面的实现效果完全一致 for species, count in sorted(species_count.items(), key=lambda x: x[0]): print(f"{species}: {count}") # 按出现频次从高到低排序 for species, count in sorted(species_count.items(), key=lambda x: x[1], reverse=True): print(f"{species}: {count}")
内容的提问来源于stack exchange,提问作者Humanperson
相关产品推荐
相关产品推荐

