简体   繁体   English

Python,将2d列表中的所有数字除以10,然后返回2d列表

[英]Python, divide all numbers in a 2d list by 10 and return a 2d list

I wrote this solution, and coming from Ruby it seems very elegant. 我编写了此解决方案,并且来自Ruby,它看起来非常优雅。 However, is this the way a python programmer would do it? 但是,这是python程序员会这样做的方式吗?

a = [[2,3,4], [9,1,2]]
print map(lambda(i): map(lambda(p): p/10.0,i), a)

And... what if instead of 10, I wanted to use the total of all the values in the nested 2d list? 并且...如果我想使用嵌套2d列表中所有值的总和,而不是10?

That's generally solved by using comprehensions, in this case a nested list-comprehension: 这通常通过使用理解来解决,在这种情况下,这是嵌套的列表理解:

>>> 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]]

That's probably faster than map and avoids all the lambda functions. 这可能比map更快,并且避免了所有lambda函数。

what if instead of 10, I wanted to use the total of all the values in the nested 2d list? 如果要使用嵌套2d列表中所有值的总和而不是10,该怎么办?

Calculate the total using sum and a nested generator expression: 使用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]]

But with NumPy arrays it's even easier. 但是使用NumPy数组则更加容易。 NumPy a 3rd party package but very powerful and fast: NumPy是第三方软件包,但功能强大且快速:

>>> 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 ]])

Another approach is to use numpy , since it deals with arrays and its operators work on each element of the array by default. 另一种方法是使用numpy ,因为它处理数组,并且其运算符默认情况下对数组的每个元素起作用。

In [1]: import numpy as np

In [2]: a = np.array([[2,3,4], [9,1,2]])

In [3]: a/10
Out[3]: 
array([[ 0.2,  0.3,  0.4],
       [ 0.9,  0.1,  0.2]])

To divide by the sum of all the numbers, do 要除以所有数字的总和,请执行

In [6]: a/a.sum()
Out[6]: 
array([[ 0.0952381 ,  0.14285714,  0.19047619],
       [ 0.42857143,  0.04761905,  0.0952381 ]])

List comprehensions are much more elegant and would be considered more Pythonic (with their better readability): 列表理解要优雅得多,并且会被认为更Pythonic(具有更好的可读性):

>>> [[x/10.0 for x in lst] for lst in a]
[[0.2, 0.3, 0.4], [0.9, 0.1, 0.2]]

Also, note that map won't return a list in Python 3, it returns an iterator object. 另外,请注意map在Python 3中不会返回列表,而是返回一个迭代器对象。 You'll need to call list on each of the map objects to have them evaluated into list. 您需要在每个地图对象上调用list ,以将它们评估为列表。 The list comp returns the same result across versions. list comp在各个版本中返回相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM