gpt4 book ai didi

Python,将二维列表中的所有数字除以 10 并返回二维列表

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:35 25 4
gpt4 key购买 nike

我写了这个解决方案,它来自 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 ]])

关于Python,将二维列表中的所有数字除以 10 并返回二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46269532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com