Convert ((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7)) to ((2,3),(7,4),(8,1),(-8,7))
It works to convert the tuple to a numpy array, and then apply .astype(int), but is there a more direct way? Also my 'solution' seems too special.
It works to use numpy
import numpy
data = ((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7))
data1 = numpy.array(data)
data2 = data1.astype(int)
data3 = tuple(tuple(row) for row in data2)
data3 # ((2, 3), (7, 4), (8, 1), (-8, 7))
((2, 3), (7, 4), (8, 1), (-8, 7)) as expected and desired
Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task.
You can pass the str() function into the map() function to convert each tuple element to a string. Then, you can join all strings together to a big string. After converting the big string to an integer, you've successfully merged all tuple integers to a big integer value.
A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function.
When it is required to convert a tuple to a float value, the 'join' method, 'float' method, 'str' method and generator expression can be used. Generator is a simple way of creating iterators.
In [16]: t = ((2.0,3.1),(7.0,4.2),(8.9,1.0),(-8.9,7))
In [17]: tuple(tuple(map(int, tup)) for tup in t)
Out[17]: ((2, 3), (7, 4), (8, 1), (-8, 7))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With