我在Python中有关于德克萨斯州婴儿名字的这个程序。解决了相当多的问题,但卡在计数部分。我将列表转换为字典。输出必须使得程序在用户提供的时间范围内显示前5个最受欢迎的婴儿名称(开始年份,结束年份)。
def count_names(file_data, begin, end, sex):
import operator as op
x=[]
c=[]
a=[]
t=[]
number_names = 5
for d in range (begin,end+1):
x.append(str(d))
for y in file_data:
if y[5:9] in x:
c.append(y)
for q in c:
p=q.split(',')
if (p[1]=='M'):
t.append(p)
elif(p[1]=='F'):
a.append(p)
if(sex=='M'):
dm={}
for h in t:
dm[h[3]]=h[4]
elif(sex=='F'):
df={}
for j in a:
df[j[3]]=j[4]
def main():
#Open the data file and save the data in a list called file_data.
#Each element of the list is a string in the format:
# 'TX,GENDER,YEAR_OF_BIRTH,BABY_NAME,OCCURRENCES\n'
file_data = open('TX19010-2016.csv').readlines()
sex = 'M'
cmd = ''
while cmd != 'quit()':
cmd = input('> ')
if cmd == 'girl':
sex = 'F'
elif cmd == 'boy':
sex ='M'
elif cmd != 'quit':
years = cmd.split()
begin = int(years[0])
if len(years) > 1:
end = int(years[1])
else:
end = begin
count_names(file_data, begin, end, sex)
main()