尝试从文件中获取特定数据并从特定数据中生成元组

时间:2017-07-16 17:36:53

标签: python python-3.x

我正在完成一项任务,并且正在尝试弄清楚如何从文件中获取某些数据(按照'标题','年',& #39;类型','导演''演员')并将其变成元组,以便我可以将其用作值的关键词 - 字典样式。我想采取'标题'和'年'并使它们像这样的元组:(' Title',' year')然后将值设为' Cast' (每个标题的演员数量各不相同)。这是我提出的,但我无法弄清楚如何从文件中取出并放入元组。任何帮助都会很棒,谢谢!

def list_maker(in_file):
    d = {}
    for line in in_file:
        l = line.split(",")
        for i in l:
            if i == l[0]:
                x = i
                print(i)
            elif i == l[1]:
                y = i
            title_year = tuple(x, y)
        print(title_year)  # checking to see if it does what I want

我收到错误:

Traceback (most recent call last):
  File "C:/PyCharmWorkspace/HW5/Problem 2(a).py", line 44, in <module>
    list_maker(in_file)
  File "C:/PyCharmWorkspace/HW5/Problem 2(a).py", line 20, in list_maker
    title_year = tuple(x, y)
UnboundLocalError: local variable 'y' referenced before assignment

1 个答案:

答案 0 :(得分:1)

正如之前的评论中所述,您正在尝试使用您可能已分配或未分配的变量。您通过for循环的第一次迭代为 x 分配值,但尚未为 y 分配值,但您尝试在元组中使用 EM>

  for i in l:   <--first iteration
       if i == l[0]:  <--- True
            x = i    <--- x is assigned the value of i
            print(i)
        elif i == l[1]:  <---- False
            y = i     <--- DOES NOT HAPPEN
        title_year = tuple(x, y)   <--- python doesn't know what y is

据说你根本不需要for循环,你可以线性地完成你的任务。

def list_maker(in_file):
    d = {}
    for line in in_file:
        l = line.split(",")
        x = l[0]
        y = l[1]
        title_year = (x, y) #this is all you need to generate a tuple
        print(title_year)  # checking to see if it does what I want