我使用多行命令将[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']
如何以优雅的方式完成这项任务?
答案 0 :(得分:13)
您需要__name__
属性。
[i.__name__ for i in Numbers]
另外,如果您有兴趣对Python数据结构进行内省,请使用dir()
。例如,dir(int)
将返回您可以在int
类型上使用的所有属性和可调用方法的列表。
答案 1 :(得分:0)
你去吧
Numbers = [int, bool ,float]
Labels = [x.__name__ for x in Numbers]
请参阅:https://docs.python.org/2/library/stdtypes.html#special-attributes和https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions以获得进一步说明。
答案 2 :(得分:0)
可能有更多的pythonic方法可以做到这一点,但适用于这些类型的1-liner是:
>>> [ x.__name__ for x in Numbers ]
['int', 'bool', 'float']
顺便说一下,您可以使用dir()
例如:
>>> dir(Numbers[0])
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
答案 3 :(得分:0)
__name__ will help you to show type of it as a string,
您可以使用dir(var)
>>> num = [1,bool(1),1.10]
>>> [type(i).__name__ for i in num]
['int', 'bool', 'float']
>>>