如何将列表中的所有整数相乘 [英] How to multiply all integers inside list
问题描述
你好,所以我想将列表中的整数相乘.
Hello so I want to multiply the integers inside a list.
例如;
l = [1, 2, 3]
l = [1*2, 2*2, 3*2]
输出:
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]
推荐答案
This goes through l
, multiplying each element by two.
当然,有多种方法可以做到这一点.如果您正在使用 lambda函数和
Of course, there's more than one way to do it. If you're into lambda functions and map
, you can even do
l = map(lambda x: x * 2, l)
将功能lambda x: x * 2
应用到l
中的每个元素.这等效于:
to apply the function lambda x: x * 2
to each element in l
. This is equivalent to:
def timesTwo(x):
return x * 2
l = map(timesTwo, l)
请注意,map()
返回一个地图对象,而不是列表,因此,如果以后确实需要列表,则可以在以后使用list()
函数,例如:
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:
l = list(map(timesTwo, l))
感谢 Minyc510在注释中这种澄清.
这篇关于如何将列表中的所有整数相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!