我使用多行命令将[int,bool,float]转换为['int','bool','float'].
Numbers = [int, bool, float]
>>> [ i for i in Numbers]
[<class 'int'>, <class 'bool'>, <class 'float'>]
>>>foo = [ str(i) for i in Numbers]
>>>foo
["<class 'int'>", "<class 'bool'>", "<class 'float'>"]
>>> bar = [ i.replace('<class ','') for i in foo]
>>> bar
["'int'>", "'bool'>", "'float'>"]
>>> baz = [i.replace('>','') for i in bar]
>>> baz
["'int'", "'bool'", "'float'"]
>>> [ eval(i) for i in baz]
['int', 'bool', 'float']
Run Code Online (Sandbox Code Playgroud)
如何以优雅的方式完成这项任务?
Jos*_*RLi 13
你想要这个__name__属性.
[i.__name__ for i in Numbers]
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果您有兴趣对Python数据结构进行内省,请使用dir().例如,dir(int)将返回可在该int类型上使用的所有属性和可调用方法的列表.