2015-10-16 66 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

谢谢。我这现在好了 –