2014-10-19 27 views
-1

對於我的Python類的作業,我們必須創建一個接受字符串S的函數,並創建一個以分號分隔的字符串數字的嵌套列表(元素必須是浮點數)。例如,字符串:將程序轉換爲Python中的函數?

「3.5 1 9.2 4 2 7 0 15 3 1 8 -2」

應產生的列表:

[[3.5,1.0,9.2,4.0] [2.0,7.0,0.0,15.0],[3.0,1.0,8.0,-2.0]

我終於能寫程序:

S = "3.5 1 9.2 4;2 7 0 15;3 1 8 -2" 
i = 0 
z = 0 
temp_list = [] 
good_list = [] 
str_temp = "" 


S_temp = S.split(";") 

while i < len(S_temp): 
    str_temp = S_temp[i] 
    temp_list = str_temp.split(" ") 
    while z < len(temp_list): 
     temp_list[z] = float(temp_list[z]) 
     z += 1 
    z = 0 
    good_list.append(temp_list) 
    i += 1 

不過,我現在卡住試圖找出如何轉換爲功能...

我想這將是沿着線:

def testfunction(S): 
    S_temp = S.split(";") 

    while i < len(S_temp): 
     str_temp = S_temp[i] 
     temp_list = str_temp.split(" ") 
     while z < len(temp_list): 
      temp_list[z] = float(temp_list[z]) 
      z += 1 
     z = 0 
     good_list.append(temp_list) 
     i += 1 

然而,當我將它保存並嘗試運行testfunction(S)(分配s到相同的字符串作爲我原來的程序後)我得到以下錯誤:

UnboundLocalError:局部變量賦值

這到底是怎麼回事之前,「我」引用?我不是要求一個直接的答案,而只是一兩個提示,以便我可以弄明白並從中學習..

謝謝。

+0

哪裏是'I = 0'在你的函數? – vks 2014-10-19 06:41:01

+0

您沒有將變量初始化設置放入您的函數中。 – BrenBarn 2014-10-19 06:42:56

回答

1

在使用它們之前,您沒有初始化變量。這是相同的情況下我,good_list和z

def testfunction(S): 
    S_temp = S.split(";") 
    i=0 
    good_list=[] 
    while i < len(S_temp): 
     str_temp = S_temp[i] 
     temp_list = str_temp.split(" ") 
     z=0 
     while z < len(temp_list): 
      temp_list[z] = float(temp_list[z]) 
      z += 1 
     z = 0 
     good_list.append(temp_list) 
     i += 1 
+0

本應該是一個評論 – vks 2014-10-19 06:45:55

+1

@vks我只是想給他看代碼。儘管如此,如果我只是提到它,他就無法得到我。 – user3378649 2014-10-19 06:47:24

0

在你,因爲你不爲i指定初始值的代碼,你明白我的錯誤! 請注意,總是需要在引用前分配變量!

作爲一個更Python的方式,你可以用list comprehension做到這一點:

>>> [map(float,n.split()) for n in s.split(';')]] 
[[3.5, 1.0, 9.2, 4.0], [2.0, 7.0, 0.0, 15.0], [3.0, 1.0, 8.0, -2.0]] 

所以創造你可以通過s作爲其參數的函數:

def seperator(s): 
return [map(float,i) for i in [n.split() for n in s.split(';')]] 
0

您獲得的原因錯誤是因爲您忘記在功能的主體中包含i = 0;您還應該包括z = 0並初始化爲good_list。在你的S_temp作業後聲明這些。

您還應該使用小寫字母作爲變量,並且在Python中,您不需要知道序列的長度就可以遍歷它。所以i真的不是必需的,也不是z。最後,你需要返回結果。

最終,你的代碼應該是這樣的:

def test_function(s): 
    good_list = [] 

    for i in s.split(';'): 
     temp_list = [] # empty list 
     for z in i.split(" "): 
      temp_list.append(float(z)) 
     good_list.append(temp_list) 

    return good_list # you forgot to return the result