在Python中,可以使用遞歸函數(shù)或者使用內(nèi)置的itertools.chain
模塊來(lái)對(duì)數(shù)組進(jìn)行扁平化處理。
def flatten_array(arr):
result = []
for i in arr:
if isinstance(i, list):
result.extend(flatten_array(i))
else:
result.append(i)
return result
# 示例
arr = [1, [2, 3], [4, [5, 6]]]
flattened_arr = flatten_array(arr)
print(flattened_arr) # 輸出:[1, 2, 3, 4, 5, 6]
itertools.chain
模塊:import itertools
def flatten_array(arr):
return list(itertools.chain.from_iterable(
(flatten_array(i) if isinstance(i, list) else [i] for i in arr)
))
# 示例
arr = [1, [2, 3], [4, [5, 6]]]
flattened_arr = flatten_array(arr)
print(flattened_arr) # 輸出:[1, 2, 3, 4, 5, 6]