【发布时间】:2019-11-22 15:41:57
【问题描述】:
我正在做这个项目,它需要从https://www.ssa.gov/oact/babynames/limits.html 的名称中获取输入 ,所以我创建了一个循环来获取文件中的所有名称,然后再创建一个循环来检查最大的名称。然而,循环似乎只运行一次并给出列表中的第一个名称。有没有办法让它通过列表?
## https://www.ssa.gov/oact/babynames/limits.html
file = open('yob2003.txt', 'r')
# variables to store the most popular name
# and the most popular name count
most_pop_name = ""
allNames = set()
count = 0
for line in file: # loop to check for names
list = line.split(',')
if int(list[2]) > 100: # not worth to work with stuff under 100
allNames.add(list[0])
print(len(allNames))
bigList = sorted(allNames)
file.close()
file = open('yob2003.txt', 'r')
for x in range(len(bigList)): # big loop that goes through once
total = 0
for line in file:
list = line.split(',')
if bigList[x] == list[0]:
total += int(list[2])
if total > count:
most_pop_name = str(list[0])
total = count
# print most popular name
print("Most popular name in [NJ] :: " + str(most_pop_name) + " " + str(count))
【问题讨论】:
-
获取yob2003需要下载全国数据,找到yob2003.txt
-
file是一个迭代器。在你的第一个循环中迭代它之后,它已经用尽了。使用seek(0)重新打开文件或将其重置到第一个位置 -
另外,最好使用某种字典,而不是为大文件中的每个条目再次读取整个文件。