Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert [int, bool ,float] to ['int', 'bool','float'] with one single line command?

Tags:

python

I convert [int, bool ,float] to ['int', 'bool','float'] using many lines of command.

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

How to accomplish such a task in an elegant manner?

like image 529
AbstProcDo Avatar asked Aug 10 '17 16:08

AbstProcDo


People also ask

Can you convert int to float?

Converting Integers to FloatsBy using the float() function, we can convert integers to floats.

How do you convert int to float in Python?

To convert the integer to float, use the float() function in Python. Similarly, if you want to convert a float to an integer, you can use the int() function.

How do you change data from one type to another in SQL?

The CONVERT() function in SQL server is used to convert a value of one type to another type. It is the target data type to which the to expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc. It provides the length of the target_type. Length is not mandatory.

How do I convert a float to a string in Python?

We can also convert a float to a string using the str() function.


1 Answers

You want the __name__ attribute.

[i.__name__ for i in Numbers]

As an aside, if you are interested in performing introspection on Python data structures, use dir(). For example, dir(int) will return a list of all attributes and callable methods you can use on the int type.

like image 71
JoshuaRLi Avatar answered Sep 23 '22 12:09

JoshuaRLi