Kivi Kivit Kivi Kivit - 1 year ago 42
Python Question

How to reach every single element which is not list in random nested list?

Assume there are a list like following, it is important to note that this is an arbitrary list, to demonstrate that list contains completely random lists with strings/numeric values:

[[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]


I want to get every single item in this list but I want to get only numbers or strings but not list. Let's say, I created a function which takes only strings, integers and float but not lists. I want to use this function.

I want to create the same list but with different object based on the function's output. Let's say function converts string to numeric value. I want to create a list like that:

[[[1],1],[2,[[123,[[[23]]],23],[12.3,23]]],[[5],1,1]]


I thought and I could not come with an answer. How can I do that?

Answer

Here is a function that resembles a very simple attempt at nested map:

def map_nested(fnc, l):
    try: 
        return fnc(l)
    except:
        return [map_nested(fnc, sub) for sub in l]

>>> l = [[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
>>> map_nested(float, l)
[[[1.0], 1.0], [2.0, [[123.0, [[[23.0]]], 23.0], [12.3, 23.0]]], [[5.0], 1.0, 1.0]]

It will apply the provided function fnc to all items in l that are valid arguments to that function (or to l itself) and attempts to iterate over the others.