![](/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.