Skip to main content
 首页 » 编程设计

python之改变列表中列表的值

2025年05月04日38bjzhanghao

我正在尝试将“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]] 

有谁知道如何获取代码来更改所有列表,而不仅仅是第一个列表?

请您参考如下方法:

Outdent return end_list 到 for 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