更改列表中列表的值

时间:2015-10-16 10:53:34

标签: python list

我试图翻译' 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 个答案:

答案 0 :(得分:3)

Outdent return end_listfor A_List in list_of_lists:缩进级别。

sub_list = []带入for - 循环:

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

答案 1 :(得分:2)

代码中有两个问题 -

  1. 您正在for循环内返回,因此您在完成第一个子列表后立即返回。因此你得到了输出。

  2. 您没有在for循环中重新定义sub_list,如果没有,只会多次添加一个sub_list,并且您对其所做的任何更改都会反映在所有子列表中。< / p>

  3. 但是你不需要这一切,你可以使用列表理解来实现同样的目标 -

    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]]
    

答案 2 :(得分: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]]