【发布时间】:2014-12-14 07:05:32
【问题描述】:
您好,我想将列表中的整数相乘。
例如;
l = [1, 2, 3]
l = [1*2, 2*2, 3*2]
输出:
l = [2, 4, 6]
所以我在网上搜索,大部分答案都是关于将所有整数相乘,例如:
[1*2*3]
【问题讨论】:
标签: python list multiplication scalar elementwise-operations
您好,我想将列表中的整数相乘。
例如;
l = [1, 2, 3]
l = [1*2, 2*2, 3*2]
输出:
l = [2, 4, 6]
所以我在网上搜索,大部分答案都是关于将所有整数相乘,例如:
[1*2*3]
【问题讨论】:
标签: python list multiplication scalar elementwise-operations
l = [x * 2 for x in l]
这通过l,将每个元素乘以二。
当然,有不止一种方法可以做到这一点。如果你喜欢lambda functions 和map,你甚至可以这样做
l = map(lambda x: x * 2, l)
将函数lambda x: x * 2 应用于l 中的每个元素。这相当于:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
注意map()返回的是一个地图对象,而不是一个列表,所以如果你之后真的需要一个列表,你可以在之后使用list()函数,例如:
l = list(map(timesTwo, l))
感谢Minyc510 in the comments 的澄清。
【讨论】:
for 循环快得多。
使用 numpy :
In [1]: import numpy as np
In [2]: nums = np.array([1,2,3])*2
In [3]: nums.tolist()
Out[4]: [2, 4, 6]
【讨论】:
#multiplying each element in the list and adding it into an empty list
original = [1, 2, 3]
results = []
for num in original:
results.append(num*2)# multiply each iterative number by 2 and add it to the empty list.
print(results)
【讨论】:
对我来说最简单的方法是:
map((2).__mul__, [1, 2, 3])
【讨论】:
如果你走这条路,另一种可能比匿名函数更容易查看的函数方法是使用 functools.partial 来利用具有固定倍数的两个参数 operator.mul
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
【讨论】:
最 Pythonic 的方式是使用列表推导:
l = [2*x for x in l]
如果您需要对大量整数执行此操作,请使用numpy 数组:
l = numpy.array(l, dtype=int)*2
最后一种选择是使用地图
l = list(map(lambda x:2*x, l))
【讨论】: