[英]How can I multiply all the elements in a list with a given constant?
[[[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]]]
I want to multiply all the numbers in this list using Python with a constant (say (-1)), but the list still has the original format.我想使用 Python 将这个列表中的所有数字乘以一个常数(比如(-1)),但该列表仍然具有原始格式。 I was trying to do that with 3 'for' loops, but is there a short way I can do this?
我试图用 3 个“for”循环来做到这一点,但有没有捷径可以做到这一点? Thanks!!
谢谢!!
The following code can multiply all of the numbers by a constant.以下代码可以将所有数字乘以一个常数。 For more advanced operations, you may want to look into
np.vectorize
or np.apply
对于更高级的操作,您可能需要查看
np.vectorize
或np.apply
import numpy as np
nested_list = [[[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0,-7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]], [[-7.0, -7.0], [-7.0, -7.0], [-7.0, -7.0]]]
numpy_list = np.array(nested_list)
negated_list = -1 * numpy_list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.