以下是一个示例代码,用于按名称取消嵌套列表:
def flatten_list(nested_list, name):
flattened_list = []
for item in nested_list:
if isinstance(item, list):
flattened_list.extend(flatten_list(item, name))
elif isinstance(item, dict) and name in item:
flattened_list.append(item[name])
return flattened_list
# 示例使用
nested_list = [1, 2, [3, 4, {'name': 'Alice', 'age': 25}], [5, {'name': 'Bob', 'age': 30}]]
flattened_list = flatten_list(nested_list, 'name')
print(flattened_list)
输出:
['Alice', 'Bob']
这个示例代码定义了一个名为flatten_list
的函数,它接受两个参数:nested_list
表示嵌套列表,name
表示要取消嵌套的字典的名称。
函数使用递归的方式遍历嵌套列表,如果遇到子列表,则递归调用自身来处理子列表。如果遇到字典,且字典包含指定的名称,则将该名称对应的值添加到结果列表中。
最后,示例演示了如何调用flatten_list
函数,并将结果打印出来。输出结果为['Alice', 'Bob']
,因为字典中的name
键的值分别为'Alice'
和'Bob'
。
上一篇:按名称求取数组的总和
下一篇:按名称筛选数组对象