我想我已经找到了一种方法来处理任何维度的数组,即使数组的元素并非都具有相同的维度,例如:
array=[
[
['N',2],
[3,'N']
],
[
[5,'N'],
7
],
]
首先,定义一个函数来检查一个变量是否是可迭代的,比如In Python, how do I determine if an object is iterable?中的那个:
def iterable(obj):
try:
iter(obj)
except Exception:
return False
else:
return True
然后,使用以下递归函数将“N”替换为 0:
def remove_N(array):
"Identify if we are on the base case - scalar number or string"
scalar=not iterable(array) or type(array)==str #Note that strings are iterable.
"BASE CASE - replace "N" with 0 or keep the original value"
if scalar:
if array=='N':
y=0
else:
y=array
"RECURSIVE CASE - if we still have an array, run this function for each element of the array"
else:
y=[remove_N(i) for i in array]
"Return"
return y
示例输入的输出:
print(array)
print(remove_N(array))
产量:
[[['N', 2], [3, 'N']], [[5, 'N'], 7]]
[[[0, 2], [3, 0]], [[5, 0], 7]]
你怎么看?