Python: Map a function over recursive iterables

后端 未结 5 2237
孤独总比滥情好
孤独总比滥情好 2021-02-13 11:42

I have an arbitrarily nested iterable like so:

numbers = (1, 2, (3, (4, 5)), 7)

and I\'d like to map a function over it without changing the st

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 12:24

    If you want to extend your result to dict, set and others, you can use Uriel's answer:

    from collections import Collection, Mapping
    
    def recursive_map(data, func):
        apply = lambda x: recursive_map(x, func)
        if isinstance(data, Mapping):
            return type(data)({k: apply(v) for k, v in data.items()})
        elif isinstance(data, Collection):
            return type(data)(apply(v) for v in data)
        else:
            return func(data)
    

    Tests input:

    recursive_map({0: [1, {2, 2, 3}]}, str)
    

    Yields:

    {0: ['1', '{2, 3}']}
    

提交回复
热议问题