2017-08-10 95 views
5

使用多行命令將[int,bool,float]轉換爲['int','bool','float']。是否可以使用一行命令將[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'] 

如何以優雅的方式完成這樣的任務?

回答

13

你想要__name__屬性。

[i.__name__ for i in Numbers] 

順便說一句,如果你有興趣在執行上的Python數據結構自省,使用dir()。例如,dir(int)將返回可在int類型上使用的所有屬性和可調用方法的列表。

0

有可能是一個更Python的方式來做到這一點,但有1襯墊,對於這些類型的工作原理是:

>>> [ 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'] 
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'] 
>>>