【问题标题】:Python: dict and sorting in alphabeticalPython:按字母顺序排列和排序
【发布时间】:2015-12-09 08:30:14
【问题描述】:

我需要编写一个程序,它接受用户输入的年份并从 CSV 文件中读取信息,然后将结果导出到屏幕上。 csv 源文件格式为:year, name, count, gender,导出结果为boy only,格式为Name Count,按字母顺序排列。

输入文件:

2010,Ruby,440,Female

2010,Cooper,493,Male

输出:

Please enter the year: 2010
Popular boy names in year 2010 are:
     Aidan  112

运行程序时出现错误:

Please enter the year: 2014
    Traceback (most recent call last):
      File "E:\SIT111\A1\printBoynameTPL.py", line 26, in <module>
        year, name, count, gender = row
    ValueError: need more than 0 values to unpack

这是我的代码:

'''
This program accepts a year as input from a user and print boys' information of the year. The output should be  sorted by name in alphabetical order.


Steps:
1. Receive a year from a user

2. Read CSV files: 
Format: year, name, count, gender

3. Display popular boy names  on the screen:
Format:    Name     Count

'''

import csv

inputYear = raw_input('Please enter the year: ')
inFile = open('output/babyQldAll.csv', 'rU')
cvsFile = csv.reader(inFile, delimiter=',')

dict = {}

for row in  cvsFile:
    year, name, count, gender = row  

    if (year == inputYear) and (gender == 'Boy'):
        dict[name] =  count

print('Popular boy names in year %s are:' % inputYear)

# +++++ You code here ++++
# According to informaiton in 'dict',  print (name, count) sorted by 'name' in alphabetical order         
sortedName = shorted(dict.keys())
for name in sortedName:
    print(name, dict[name])
print("Print boy names... ")    


inFile.close()

我编辑了一下:

for row in  cvsFile:
        if row:
            year, name, count, gender = row  

            if (year == inputYear) and (gender == 'Male'):
                dict[name] =  count  
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict',  print (name, count) sorted by 'name' in alphabetical order         
sortedName = sorted(dict.keys())
for name in sortedName:
        print(name,dict[name])
print("Print boy names... ")    

我做错了吗?缩进还是……?

结果:

>>> 
Please enter the year: 2013
Popular boy names in year 2013 are:
Print boy names... 
>>> 

【问题讨论】:

    标签: python sorting csv dictionary


    【解决方案1】:

    您的 csv 文件中似乎有空行,这导致空的 row 来迭代 csv 文件。在执行其余逻辑之前,您可以简单地检查 row 是否为空。示例 -

    for row in  cvsFile:
        if row:
            year, name, count, gender = row  
    
            if (year == inputYear) and (gender == 'Boy'):
                dict[name] =  count
    

    另外,你不应该使用dict作为变量名,它会影响内置函数dict()

    另外,你的程序中还有一个错字 -

    sortedName = shorted(dict.keys())
    

    我猜你打算使用sorted()

    【讨论】:

    • 天啊!这是我的拼写错误。现在它工作正常,但没有结果导出到屏幕。请输入年份:2013 2013年流行的男孩名字有:打印男孩名字...
    • 我注意到在实际的 csv 中你有 Male / Female 。但是为了检查您是否使用 Boy ,这可能是问题吗?
    • 我改成 'male' 但还是一样的问题,没有导出
    • capital M 男性?在比较之前尝试打印每个元素,如果没有得到任何结果,则表示条件不满足一行。
    • 是的,'男性',但它不起作用。但在我的 csv 文件中,每个元素中都有一个空行等:2010,Chloe,398,Female 一行空白和 2010,Lachlan,430,Male 是否影响此代码?
    最近更新 更多