0

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?

kimimki
  • 65
  • 1
  • 7

2 Answers2

0

You probably want to traverse your entire structure recursively, and either store the results or call your function on the results right there. It would look something like this:

sample = [[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
def traverse(l, f):
    result = []
    for item in l:
        if isinstance(item, list):
            result.append(traverse(item))
        else:
            result.append(f(item))
    return result
amiller27
  • 491
  • 5
  • 8
  • Thans for your reply, But when I use this, I end up with different list, if i use a function "float()" [1.2, 1.0, 2.0, 12.3, 23.0, 23.0, 12.3, 23.0, 5.0, 1.0, 1.0] – kimimki May 15 '16 at 18:53
  • if you change extend to append and if ı use my function inside of else: result.append(myfunction(item)),,, this solution also works – kimimki May 15 '16 at 19:09
  • I see, I didn't realize you wanted your output to remain in the same structure as the original. – amiller27 May 15 '16 at 19:25
0

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89