[英]Python: an elegant way to extract floats from list?
Is there a more elegant way to do this? 有没有更优雅的方法可以做到这一点?
I have a "double" list of the form: 我有以下形式的“双重”清单:
rlist = [([-0.5753647], [1.3716470]), ([-0.57536478], [0.75418190]), ([-1.37632438], [0.57068748])]
from which I want to extract individual floating point numbers, formatted. 我想从中提取格式化的单个浮点数。
At the moment I'm using: 目前,我正在使用:
first_number = round(float(str(rlist[0][0]).strip('[]')),4)
for example, to get the first number. 例如,获取第一个数字。 This is rather ugly.
这很丑。 Is there a more succinct way to do it (in Python)?
是否有更简洁的方法(在Python中)?
DN DN
You can try something like this: 您可以尝试如下操作:
from itertools import chain
[round(x, 4) for x in chain(*chain(*rlist))]
itertools.chain
can be used to flatten nested iterables. itertools.chain
可用于展平嵌套的可迭代对象。 After that you can use list comprehension and round
to obtain list of numbers with required precision. 之后,您可以使用列表理解和
round
来获得具有所需精度的数字列表。
If you are opting for itertools.chain()
, if level of nesting is more please see the comments below this answer
by @zero323 如果您选择
itertools.chain()
,则如果嵌套级别更高, please see the comments below this answer
通过@ zero323 please see the comments below this answer
And round() has also some restrictions too, 而且round()也有一些限制,
f = -0.5753647
print f
-0.57536469999999995
print round(f, 4)
-0.57540000000000002
So, 所以,
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.