2015-10-16 68 views
1

我試圖將'methuselahs'翻譯成二進制代碼。所有的點('。')應該變爲0,並且所有的O('O')應該變爲1.更改列表中的列表的值

我目前有一個可以工作的代碼,但它只會返回第一個list_of_lists列表。

list_of_lists = [['.O'],['...O'],['OO..OOO']] 

def read_file(list_of_lists): 

    """Reads a file and returns a 2D list containing the pattern. 
    O = Alive 
    . = Dead 
    """ 

    end_list = [] 
    sub_list = [] 

    for A_List in list_of_lists: 
     for A_String in A_List: 
      for item in A_String: 

#Adding 0's and 1's to sub_list when given the right input 
       if item == '.': 

        sub_list.append(0) 

       elif item == 'O': 

        sub_list.append(1) 

#Adding the sub 
      end_list.append(sub_list) 

     return end_list 

輸出:

[[0,1]] 

但預期輸出:

[[0,1],[0,0,0,1],[1,1,0,0,1,1,1]] 

有誰知道我可以讓代碼更改所有列表,而不僅僅是第一個?

回答

3

Outdent return end_listfor A_List in list_of_lists:縮進級別。

而帶來sub_list = []for -loop:

def read_file(list_of_lists): 
    """Reads a file and returns a 2D list containing the pattern. 
    O = Alive 
    . = Dead 
    """ 
    end_list = [] 
    for A_List in list_of_lists: 
     sub_list = [] 
     for A_String in A_List: 
      for item in A_String: 
      #Adding 0's and 1's to sub_list when given the right input 
       if item == '.': 
        sub_list.append(0) 
       elif item == 'O': 
        sub_list.append(1) 
      #Adding the sub 
      end_list.append(sub_list) 
    return end_list 
+0

非常感謝您!我已經搞了兩個小時,現在我明白我做錯了什麼。也感謝您的快速回復! –

2

代碼中的兩個問題 -

  1. 您從for環內返回,因此你只要你完成返回第一個子列表。因此你得到的輸出。

  2. 您不在for循環中重新定義sub_list,沒有多次添加一個sub_list,您所做的任何更改都會反映在所有子列表中。

但是你並不需要這一切,你可以使用列表解析來實現同樣的事情 -

def read_file(list_of_lists): 
    return [[1 if ch == 'O' else 0 
      for st in sub_list for ch in st] 
      for sub_list in list_of_lists] 

演示 -

>>> def read_file(list_of_lists): 
...  return [[1 if ch == 'O' else 0 
...    for st in sub_list for ch in st] 
...    for sub_list in list_of_lists] 
... 
>>> read_file([['.O'],['...O'],['OO..OOO']]) 
[[0, 1], [0, 0, 0, 1], [1, 1, 0, 0, 1, 1, 1]] 
+0

我永遠不會想出這樣的解決方案,但它完美的作品!感謝您回答這麼快! –

+0

很高興我能幫到你! :-)。此外,如果您發現答案有幫助,我希望您請求您接受答案(通過點擊答案左側的勾號),無論您最喜歡哪個答案,都會對社區有所幫助。 –

0

您的代碼就可以了。但問題在return end_list縮進級別。當您返回for loop時,在第一次迭代之後,您的函數將返回並且不會發生其他迭代。

試試這個,你的代碼被修改:

list_of_lists = [['.O'],['...O'],['OO..OOO']] 

def read_file(list_of_lists): 

    """Reads a file and returns a 2D list containing the pattern. 
    O = Alive 
    . = Dead 
    """ 

    end_list = [] 

    for A_List in list_of_lists: 
     sub_list = [] 
     for A_String in A_List: 
      for item in A_String: 

#Adding 0's and 1's to sub_list when given the right input 
       if item == '.': 

        sub_list.append(0) 

       elif item == 'O': 

        sub_list.append(1) 

#Adding the sub 
      end_list.append(sub_list) 

    return end_list 

輸出:

[[0,1],[0,0,0,1],[1,1,0,0,1,1,1]] 
+0

謝謝。我這現在好了 –