[英]Manipulating every element in an n-level deep list of lists in python
Assuming we have a list of lists:假设我们有一个列表列表:
list_of_lists = [['a','b'],['x','y','z']]
What could be considered as an efficient way to assign a value for each element?什么可以被认为是为每个元素分配值的有效方法?
new_list_of_lists = assign_value_to_all_elements(list_of_lists,'0')
print(new_list_of_lists)
>> [['0','0'],['0','0','0']]
A non-efficient way that comes to my mind is:我想到的一种非有效方式是:
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
We even cannot do this with a numpy array:我们甚至不能用 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
Only when both lists are the same size, it works:只有当两个列表大小相同时,它才有效:
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')
In the example, we are working with list of lists (2 levels deep).在示例中,我们正在使用列表列表(2 级深)。
However this could be generalized to list of list of... lists (n levels deep).但是,这可以概括为...列表列表(n 级深)。
Is there a general way to assign to or manipulate every 'base element' (by which i mean type(element)?=list ) in an n-level deep list of lists?是否有一种通用方法可以分配或操作 n 级深度列表列表中的每个“基本元素”(我的意思是 type(element)?=list )?
We will use recursion here since we don't want to write n
for-loops and cannot do it anyway as the depth of your list of lists is not known in advance.我们将在这里使用递归,因为我们不想编写
n
for 循环并且无论如何都不能这样做,因为您的列表列表的深度是事先不知道的。
The trick is to call the function again if the currently viewed element is a list, or replace its value with value
if it's not.诀窍是如果当前查看的元素是列表,则再次调用 function,如果不是,则将其值替换为
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]]]]]]]]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.