Python 如何将列表中的所有整数相乘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26446338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to multiply all integers inside list
提问by Andre
Hello so I want to multiply the integers inside a list.
您好,所以我想将列表中的整数相乘。
For example;
例如;
l = [1, 2, 3]
l = [1*2, 2*2, 3*2]
output:
输出:
l = [2, 4, 6]
So I was searching online and most of the answers were regarding multiply all the integers with each other such as:
所以我在网上搜索,大部分答案都是关于将所有整数相乘,例如:
[1*2*3]
[1*2*3]
采纳答案by APerson
Try a list comprehension:
尝试列表理解:
l = [x * 2 for x in l]
This goes through l, multiplying each element by two.
这通过l,将每个元素乘以 2。
Of course, there's more than one way to do it. If you're into lambda functionsand map, you can even do
当然,有不止一种方法可以做到。如果您喜欢lambda 函数和map,您甚至可以这样做
l = map(lambda x: x * 2, l)
to apply the function lambda x: x * 2to each element in l. This is equivalent to:
将函数lambda x: x * 2应用于l. 这相当于:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
Note that map()returns a map object, not a list, so if you really need a list afterwards you can use the list()function afterwards, for instance:
请注意,它map()返回的是一个地图对象,而不是一个列表,所以如果您之后确实需要一个列表,您可以在list()之后使用该函数,例如:
l = list(map(timesTwo, l))
Thanks to Minyc510 in the commentsfor this clarification.
感谢Minyc510 在此澄清的评论中。
回答by Joshua
The most pythonic way would be to use a list comprehension:
最 Pythonic 的方法是使用列表理解:
l = [2*x for x in l]
If you need to do this for a large number of integers, use numpyarrays:
如果您需要对大量整数执行此操作,请使用numpy数组:
l = numpy.array(l, dtype=int)*2
A final alternative is to use map
最后一个选择是使用 map
l = list(map(lambda x:2*x, l))
回答by miradulo
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partialto utilize the two-parameter operator.mulwith a fixed multiple
另一种函数式方法可能比匿名函数更容易看,如果你走那条路的话,它是使用具有固定倍数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]
回答by blameless75
The simplest way to me is:
对我来说最简单的方法是:
map((2).__mul__, [1, 2, 3])
回答by Jonathan Akwetey Okine
#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)
回答by ilya shusterman
using numpy :
使用 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]

