Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert tuple of tuples of floats to ints

Tags:

int

python-3.x

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

like image 506
David Epstein Avatar asked Jul 25 '19 20:07

David Epstein


People also ask

How do you convert a float tuple to an int tuple in Python?

Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task.

How do you convert tuples to integers?

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.

How do you convert a float to an int in Python?

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.

How do you convert a tuple to a float?

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.


1 Answers

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))
like image 115
inspectorG4dget Avatar answered Oct 12 '22 22:10

inspectorG4dget