“地图"Python 中的嵌套列表 [英] "Map" a nested list in Python

查看:52
本文介绍了“地图"Python 中的嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我试图将运算符应用于两层嵌套数组.例如,

In Python, I am trying to apply an operator to a two layer nested array. For example,

a = [['2.3','.2'],['-6.3','0.9']]
for j in range(2)
    for i in range(2)
        a[i][j] = float(a[i][j])

没有循环我怎么能做到这一点?我希望有类似于 a= map(float,a) 的东西.当然,最后一个脚本不适用于嵌套列表.单行列表理解也可以接受.

How can I do this without the loops? I am hoping for something akin to a= map(float,a). Of course the last script does not work for a nested list. A one line list comprehension may be acceptable too.

推荐答案

结合 map 和 listcomp 的单线:

One-liner with mix of map and listcomp:

a = [map(float, suba) for suba in a]  # Only works on Py2

或变体:

# Both of the below work on Py2 and Py3
a = [list(map(float, suba)) for suba in a]
a = [[float(x) for x in suba] for suba in a]

根据您的个人喜好和目标 Python 版本进行选择.对于 CPython 2 上的大型嵌套列表,第一个变体可能是最快的(如果内部列表很大,它避免了获取 float 构造函数和内部 列表的字节码执行的查找开销s),并且 list 包装的等价物可能最终会在 CPython 3 上获胜;对于所有版本的小型嵌套列表,嵌套列表推导式通常是最快的.

Choose based on your personal preference and target Python version. For large nested lists on CPython 2, the first variant is probably the fastest (if the inner lists are huge, it avoids lookup overhead to get the float constructor and byte code execution for the inner lists), and the list wrapped equivalent might eventually win on CPython 3; for small nested lists on all versions, the nested list comprehensions is usually going to be the fastest.

这篇关于“地图"Python 中的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆