Convert tuple of tuples of floats to ints

时间秒杀一切 提交于 2020-12-10 08:44:47

问题


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


回答1:


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))


来源:https://stackoverflow.com/questions/57209989/convert-tuple-of-tuples-of-floats-to-ints

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!