从嵌套数组中获取值可以通过递归或迭代的方式进行操作。以下是两种常见的方法:
def get_value_recursive(arr, target):
for item in arr:
if isinstance(item, list):
result = get_value_recursive(item, target)
if result is not None:
return result
elif item == target:
return item
return None
示例用法:
nested_array = [1, 2, [3, 4, [5, 6]], 7, [8, [9, 10]]]
target_value = 6
result = get_value_recursive(nested_array, target_value)
print(result) # 输出:6
def get_value_iterative(arr, target):
stack = [arr]
while stack:
current = stack.pop()
for item in current:
if item == target:
return item
elif isinstance(item, list):
stack.append(item)
return None
示例用法:
nested_array = [1, 2, [3, 4, [5, 6]], 7, [8, [9, 10]]]
target_value = 6
result = get_value_iterative(nested_array, target_value)
print(result) # 输出:6
以上两种方法都可以从嵌套数组中获取目标值。在实际应用中,可以根据具体情况选择适合的方法。
领取专属 10元无门槛券
手把手带您无忧上云