操作 python 中 n 级深度列表列表中的每个元素

Manipulating every element in an n-level deep list of lists in python

假设我们有一个列表列表:

list_of_lists = [['a','b'],['x','y','z']]

什么可以被认为是为每个元素赋值的有效方法?

new_list_of_lists = assign_value_to_all_elements(list_of_lists,'0') 
print(new_list_of_lists) 
>> [['0','0'],['0','0','0']]

我想到的一个低效的方法是:

def assign_value_to_all_elements(list_of_lists, new_value = '0'):
    for i in range(len(list_of_lists)):
        for j in range(len(list_of_lists[i])):
            list_of_lists[i][j] = new_value
    return list_of_lists

我们甚至不能用 numpy 数组做到这一点:

import numpy as np
list_of_lists_as_np_array = np.array([['a','b'],['x','y','z']])
list_of_lists_as_np_array[:,:] = '0'
Traceback (most recent call last):
  File "<ipython-input-17-90ee38fde5f2>", line 3, in <module>
    list_of_lists_as_np_array[:,:] = '0'
IndexError: too many indices for array

只有当两个列表大小相同时,它才有效:

import numpy as np
   ...: list_of_lists_as_np_array = np.array([['a','b'],['x','y']])
   ...: list_of_lists_as_np_array[:,:] = '0'
   ...: list_of_lists_as_np_array
Out[23]: 
array([['0', '0'],
       ['0', '0']], dtype='<U1')

在示例中,我们使用的是列表列表(2 层深)。

然而,这可以概括为列表的列表...列表(n 级深)。

是否有一种通用的方法来分配或操作 n 级深度列表列表中的每个 'base element'(我指的是 type(element)!=list )?

我们将在这里使用递归,因为我们不想写 n for-loops 并且无论如何也不能这样做,因为您的列表列表的深度事先不知道。

诀窍是如果当前查看的元素是列表,则再次调用该函数,如果不是,则将其值替换为 value

def assign_value_to_all_elements(nested_list, value):
    for n, element in enumerate(nested_list):
        if type(element) is list:
            assign_value_to_all_elements(element, value) # Same work but on a smaller
                                                         # segment of the initial list!
        else:
            nested_list[n] = value

l = [['a', 'b'], ['x', 'y', 'z'], [[1, 2, 3, [4, 5, 6]]], [[[[[[[[None]]]]]]]]]
assign_value_to_all_elements(l, 0)
print(l)
>>> [[0, 0], [0, 0, 0], [[0, 0, 0, [0, 0, 0]]], [[[[[[[[0]]]]]]]]]