2017-07-16 104 views
-1

我正在處理一個任務,並試圖弄清楚如何從文件中獲取某些數據(按'標題'排序, '年','流派','導演','演員'),並將其製作成元組,以便我可以將其用作值字典樣式的關鍵。我想把'標題'和'年份'作爲一個元組,如下所示:('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

這不是很清楚。你能添加你的輸入和期望的輸出嗎? –

+1

根據'i'的值,'x'或'y'(或者它們中沒有一個)被定義,但從來都不是。 –

+0

這也是一個學習和獲得社區人士幫助的網站。你真的希望你的名字是@Buttscratcher? – bravosierra99

回答

1

正如在評論前文所述,您嘗試使用您可能會或可能不會分配一個變量。通過你的第一個迭代循環中,您分配一個值X,但還沒有賦值給Ÿ,但你嘗試使用它在元組

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 

話雖這麼說,你不」的根本不需要循環,你可以線性地完成你的任務。

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 
+0

爲什麼'元組(x,y)'而不是'(x,y)'?或者只是:'title_year =(l [0],l [1])' –

+0

我通常會嘗試改變儘可能少的代碼來解釋發佈者遇到的問題。但在這種情況下,我認爲你是對的,更新... – bravosierra99

相關問題