【问题标题】:Python Loop Only Iterating once with Large loop which takes input from a filePython循环仅使用从文件输入的大循环迭代一次
【发布时间】: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)重新打开文件或将其重置到第一个位置
  • 另外,最好使用某种字典,而不是为大文件中的每个条目再次读取整个文件。

标签: python list loops file


【解决方案1】:

循环的问题是您执行for line in file。每次从文件中读取一行时,它都会将文件中的读取指针前进一行。所以你的大循环第一次运行时,它会到达内部循环并到达文件的末尾。因此,通过大循环的所有后续迭代都到达内部循环,注意文件已到达末尾,跳过它并继续。

您将要为您的大循环的每次迭代重新打开文件(将 file = open('yob2003.txt', 'r') 移动到您的 for x in range(len(bigList)): 之后。

旁注:不要将变量命名为 list,因为 list 指的是 Python 数据结构 list()。这种重新定义可能会在以后引起混淆和错误,所以请小心。

效率说明:您经常打开文件并执行大量循环。使用字典执行第一个循环中的所有内容可能会更好。例如:

import collections

file = open('yob2003.txt', 'r')
most_pop_name = ""
max_count = 0
counts = collections.defaultdict(int)

for line in file:
    arr = line.split(',')
    if int(arr[2]) < 100: continue

    counts[arr[0]] += int(arr[2])
    if counts[arr[0]] > max_count:
        max_count = counts[arr[0]]
        most_pop_name = arr[0]

# Python 2
print("Most popular name in [NJ] :: " + most_pop_name + " " + str(max_count))
# Python < 3.6
print("Most popular name in [NJ] ::", most_pop_name, max_count)
# Python >= 3.6
print(f"Most popular name in [NJ] :: {most_pop_name} {max_count}")

【讨论】:

  • 我遇到了很多麻烦并创建了stackoverflow帐户只是为了发布这个。该列表之所以命名,是因为作业是通过模板给出的,并且出于评分目的,我不会更改它。我会将这些收藏品用于将来之类的事情,谢谢!
  • 明白,很高兴该解决方案对您有所帮助! :)
猜你喜欢
  • 1970-01-01
  • 2016-05-10
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 2016-06-19
相关资源
最近更新 更多