Bence tek fonksiyonda cozmeye calismaya gerek yok.
Once esas listeyi flatten edersin, sonra da toplarsin icindeki elemanlari.
Toplama islemi degisme ozelligi tasidigindan reduce edebilirsin sonrasinda.
[CODE lang="python" title="flatten -> reduce"]from functools import reduce
def flatten(ls):
flattened = []
for e in ls:
if isinstance(e, list):
flattened.extend(flatten(e))
else:
flattened.append(e)
return flattened
def reduction(x, y):
x_int = isinstance(x, int)
y_int = isinstance(y, int)
if x_int and y_int:
return x + y
elif x_int:
return x
elif y_int:
return y
else:
return 0
het_list = [1, 2, 3, "a", "b", ["x", "y"], 5, [1, "p", 2, 3], "q", True, ["k", ["p", [1]]]]
print(reduce(reduction, flatten(het_list), 0))
[/CODE]
Daha kisa bir cozum de flatten -> filter -> sum olabilir.
[CODE lang="python" title="flatten -> filter -> sum"]def flatten(ls):
flattened = []
for e in ls:
if isinstance(e, list):
flattened.extend(flatten(e))
else:
flattened.append(e)
return flattened
def predicate(x):
return isinstance(x, int)
het_list = [1, 2, 3, "a", "b", ["x", "y"], 5, [1, "p", 2, 3], "q", True, ["k", ["p", [1]]]]
print(sum(filter(predicate, flatten(het_list))))
[/CODE]