Python - 列表未定义

时间:2017-11-19 21:17:56

标签: python-3.x

from typing import List, Tuple, Dict, TextIO
def names(file:TextIO) -> None:
    """ create a list with all the names from the file
    """
    lines = ""
    firstname = ""
    lastname = ""
    name_list = []
    file = open(file, 'r')
    for line in file:
      line = line.strip()
      lines += line
    for i in range(len(lines)):
      if lines[i] == ",":
        lastname += lines[i+2]
        first = i
        last = i + 3
      while lines[first].islower() and lines[last].islower():
        firstname += lines[first]
        lastname += lines[last]
        first -= 1
        last += 1
    name_list.append(firstname + " " + lastname)

继续返回name_list没有定义,哪里出错了?

1 个答案:

答案 0 :(得分:0)

我尝试了你的代码,但我没有得到同样的错误。也许在代码中检查缩进是否正确?

另一方面,你有一个问题:

  if lines[i] == ",":
    lastname += lines[i+2]
    first = i
    last = i + 3

您在if块中声明了局部变量,稍后会在代码中看不到它们,例如之后的while循环中。

您需要在块中声明变量,使用它们的所有后续块都可以看到这些变量。

我的建议是将它们添加到函数顶部的变量中:

lines = ""
firstname = ""
lastname = ""
name_list = []
lines = 0 # or whatever value it's supposed to start with
last = 0  # or whatever value it's supposed to start with