我写了这个解决方案,它来自 Ruby,看起来非常优雅。然而,这是 python 程序员会做的方式吗?
a = [[2,3,4], [9,1,2]]
print map(lambda(i): map(lambda(p): p/10.0,i), a)
而且...如果我想使用嵌套二维列表中所有值的总和而不是 10 会怎么样?
请您参考如下方法:
这通常通过使用理解来解决,在本例中是嵌套的列表理解:
>>> from __future__ import division # for python-2.x compatibility
>>> [[item / 10 for item in subl] for subl in a]
[[0.2, 0.3, 0.4], [0.9, 0.1, 0.2]]
这可能比 map 更快,并且避免了所有 lambda 函数。
what if instead of 10, I wanted to use the total of all the values in the nested 2d list?
使用sum 和嵌套生成器表达式计算总数:
>>> sum_ = sum(item for subl in a for item in subl)
>>> [[item / sum_ for item in subl] for subl in a]
[[0.09523809523809523, 0.14285714285714285, 0.19047619047619047],
[0.42857142857142855, 0.047619047619047616, 0.09523809523809523]]
但是有了 NumPy 数组,它就更容易了。 NumPy 是一个第 3 方包,但非常强大和快速:
>>> import numpy as np
>>> arr = np.array(a)
>>> arr / 10. # element-wise division
array([[ 0.2, 0.3, 0.4],
[ 0.9, 0.1, 0.2]])
>>> arr / arr.sum() # sum over all elements then element-wise division
array([[ 0.0952381 , 0.14285714, 0.19047619],
[ 0.42857143, 0.04761905, 0.0952381 ]])
