How to determine type of nested data structures in Python?

后端 未结 2 729
攒了一身酷
攒了一身酷 2021-01-12 07:55

I am currently translating some Python to F#, specifically neural-networks-and-deep-learning .

To make sure the data structures are correctly translated the details o

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 08:37

    As I commented, this is impossible in Python, because lists are untyped.

    You can still pretend to do it:

    def typ(something, depth=0):
        if depth > 63:
            return "..."
        if type(something) == tuple:
            return ">"
        elif type(something) == list:
            return ""
        else:
            return str(type(something))
    

    That returns the string >>,>>> for your example.

    edit: To make it look more like F# you could do this instead:

    def typ(something, depth=0):
        if depth > 63:
            return "..."
        if type(something) == tuple:
            return " * ".join(typ(ding, depth+1) for ding in something)
        elif type(something) == list:
            return (typ(something[0]) if something else 'empty') + " []"
        else:
            return str(type(something, depth+1)).split("'")[1]
    

    which will return int [] [] * str [] in your example.

提交回复
热议问题