为什么不回答答案?
x=[1,2,3]
y=[2,4,6]
xy = []
def mult_list(xy):
for i in range(0, len(x)):
xy.append(x[i]*y[i])
return xy
答案 0 :(得分:2)
确保缩进正确无误。 return xy
应该在循环之外。
最好不要将xy
作为全局列表。相反,在函数内部定义它。如果它是全局的,如果多次调用mul_list
,您将获得有趣的结果。
def mult_list(list_a, list_b):
xy = []
for i in range(0, len(list_a)):
xy.append(list_a[i] * list_b[i])
return xy
x = [1, 2, 3]
y = [2, 4, 6]
print(mult_list(x, y))
# [2, 8, 18]
但是,为了索引列表,使用range
被认为不是pythonic。相反,您可以使用zip
:
def mult_list(list_a, list_b):
xy = []
for num_a, num_b in zip(list_a, list_b):
xy.append(num_a * num_b)
return xy
x = [1, 2, 3]
y = [2, 4, 6]
print(mult_list(x, y))
# [2, 8, 18]
答案 1 :(得分:1)
x=[1,2,3]
y=[2,4,6]
res=[i*j for i,j in zip(x,y)]
我在这里做的是使用zip函数.zip()函数采用iterables(可以是零或更多),使迭代器根据传递的迭代次数聚合元素,并返回元组的迭代器。
示例:
numberList = [1, 2, 3]
strList = ['one', 'two', 'three']
# No iterables are passed
result = zip()
# Converting itertor to list
resultList = list(result)
print(resultList)
# Two iterables are passed
result = zip(numberList, strList)
# Converting itertor to set
resultSet = set(result)
print(resultSet)
输出:
[]
{(2, 'two'), (3, 'three'), (1, 'one')}