[英]How do you multiply the first element in a list by a number (in a list of lists) in Python?
I have a list of lists like this: 我有一个这样的清单清单:
[[1,2,3],[4,5,6]]
I would like to multiply the first element of each of the inner lists by 10. So the expected output would be this: 我想将每个内部列表的第一个元素乘以10。因此,预期的输出将是这样的:
[[10,2,3],[40,5,6]]
How could I do this? 我该怎么办?
Try this: 尝试这个:
my_list = [[1,2,3],[4,5,6]]
for i in my_list:
i[0] *= 10 # multiply the first element of each of the inner lists by 10
print(my_list)
Output: 输出:
[[10, 2, 3], [40, 5, 6]]
If you're working with large arrays, then numpy
works better than python alone, for many other reasons as well. 如果您使用的是大型数组,那么
numpy
效果比单独使用python还要好,还有许多其他原因。
lst = [[1,2,3],[4,5,6]] # if you have your list in python
lst = np.array(lst) # simple one-liner to convert to an array
lst
Out[32]:
array([[1, 2, 3],
[4, 5, 6]])
lst[:,0] *= 10 # multiply first column only by 10. This removes the need
# for python's "for" loops, which improves performance
# on larger arrays
lst
Out[34]:
array([[10, 2, 3],
[40, 5, 6]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.