![](/img/trans.png)
[英]Elegant way to extract a tuple from list of tuples with minimum value of element
[英]Python: an elegant way to extract floats from list?
有没有更优雅的方法可以做到这一点?
我有以下形式的“双重”清单:
rlist = [([-0.5753647], [1.3716470]), ([-0.57536478], [0.75418190]), ([-1.37632438], [0.57068748])]
我想从中提取格式化的单个浮点数。
目前,我正在使用:
first_number = round(float(str(rlist[0][0]).strip('[]')),4)
例如,获取第一个数字。 这很丑。 是否有更简洁的方法(在Python中)?
DN
您可以尝试如下操作:
from itertools import chain
[round(x, 4) for x in chain(*chain(*rlist))]
itertools.chain
可用于展平嵌套的可迭代对象。 之后,您可以使用列表理解和round
来获得具有所需精度的数字列表。
如果您选择itertools.chain()
,则如果嵌套级别更高, please see the comments below this answer
通过@ zero323 please see the comments below this answer
而且round()也有一些限制,
f = -0.5753647
print f
-0.57536469999999995
print round(f, 4)
-0.57540000000000002
所以,
rlist = [([-0.5753647], [1.3716470]),
([-0.57536478], [0.75418190]),
([-1.37632438], [0.57068748])]
def flatten(container):
for i in container:
if isinstance(i, list) or isinstance(i, tuple):
for j in flatten(i):
yield j
else:
yield i
print ["{0:.4f}".format(ele) for ele in list(flatten(rlist))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.