如何使用函数将列表相乘? [英] How do I multiply lists together using a function?
问题描述
如何使用函数在python中将列表相乘?这就是我所拥有的:
how do I multiply lists together in python using a function? This is what I have:
list = [1, 2, 3, 4]
def list_multiplication(list, value):
mylist = []
for item in list:
for place in value:
mylist.append(item*value)
return mylist
所以我想用它来乘以list * list(1 * 1、2 * 2、3 * 3、4 * 4)
So I want to use this to multiply list*list (1*1, 2*2, 3*3, 4*4)
所以输出将是1、4、9和16.我将如何在python中执行此操作,其中第二个列表可能是什么? 谢谢
So the output would be 1, 4, 9, and 16. How would I do this in python where the 2nd list could be anything? Thanks
推荐答案
我最喜欢的方法是将mul
运算符映射到两个列表上:
My favorite way is mapping the mul
operator over the two lists:
from operator import mul
mul(2, 5)
#>>> 10
mul(3, 6)
#>>> 18
map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10])
#>>> <map object at 0x7fc424916f50>
map
(至少在Python 3中)返回生成器.因此,如果您想要一个列表,则应将其转换为一个列表:
map
, at least in Python 3, returns a generator. Hence if you want a list you should cast it to one:
list(map(mul, [1, 2, 3, 4, 5], [6, 7, 8, 9, 10]))
#>>> [6, 14, 24, 36, 50]
但是到那时,对zip
列表使用列表理解可能更有意义.
But by then it might make more sense to use a list comprehension over the zip
'd lists.
[a*b for a, b in zip([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])]
#>>> [6, 14, 24, 36, 50]
为了解释最后一个,zip([a,b,c], [x,y,z])
给出了(生成器)[(a,x),(b,y),(c,z)]
.
To explain the last one, zip([a,b,c], [x,y,z])
gives (a generator that generates) [(a,x),(b,y),(c,z)]
.
for a, b in
将每个(m,n)
对解包"为变量a
和b
,然后将它们乘以a*b
.
The for a, b in
"unpacks" each (m,n)
pair into the variables a
and b
, and a*b
multiplies them.
这篇关于如何使用函数将列表相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!