如何使用raw_input从csv文件打印元素?
代码:
import csv
inputYear = raw_input('Please enter the year: ')
inFile = open('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)
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
print("Print boy names... ")
inFile.close()
期望的输出:
2010年流行的男孩名字是: 艾丹112 艾登168 亚历克斯93
答案 0 :(得分:0)
有很多可行的方法可以做到这一点
其中之一就是建立一个以年份为关键词的词典,值是列表,如[[John, 124, Male], [Amy, 111, Female]]
,即表示名称,计数和性别的对。
您可以构建完整的字典,然后获取每年的值:
import csv
inputYear = raw_input('Please enter the year: ')
inFile = open('babyQldAll.csv', 'rU')
cvsFile = csv.reader(inFile, delimiter=',')
dict = {}
for row in cvsFile:
year, name, count, gender = row
if dict.get(year, None): #If key in dict already
dict[year].append([name, count, gender])
else: #else, create the key
dict[year] = [[name, count, gender]]
data = ", ".join(" ".join(z) for z in dict.get(inputYear,[]) if z[3]=='Male')
if len(data):
print 'Popular boy names in {} are: {}'.format(inputYear, data)
inFile.close()
答案 1 :(得分:0)
你可以试试这个:
inputYear = raw_input('Please enter the year: ')
file1 = open('babyQldAll.csv','r')
fileContent = file1.readlines()
fileRows = fileContent[0].split("\\n")
dict = {}
for row in fileRows:
year = row.split(',')[0].strip()
name = row.split(',')[1].strip()
count = row.split(',')[2].strip()
gender = row.split(',')[3].strip()
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
odDict = sorted(dict.items())
str = ''
for i in odDict:
str = str + i[0] + ' ' + i[1] + ' '
print('Popular boy names in year '+ inputYear + ' are: ' + str)
file1.close()