如何在python中将2个输入列表相乘

时间:2020-05-17 00:18:28

标签: python-3.x

请帮助我了解如何使用输入在Python中编写以下任务

编程挑战说明: 编写一个简短的Python程序,该程序采用长度为n的两个数组a和b 存储int值,并返回a和b的点积。也就是说,它返回 长度为n的数组c,使得c [i] = a [i]·b [i],对于i = 0,...,n-1。

测试输入: List1的输入==> 1 2 3 List2的输入==> 2 3 4

预期输出:2 6 12

4 个答案:

答案 0 :(得分:4)

请注意,点积在数学中定义为要构建的向量c的元素之和。

也就是说,这是使用zip的可能性:

c = [x * y for x, y in zip(a, b)]

数学点积将为:

sum(x * y for x, y in zip(a, b))

如果从键盘上读取列表,它们将被读为字符串,您必须先进行转换,然后再应用上面的代码。

例如:

a = [int(s) for s in input().split(",")]
b = [int(s) for s in input().split(",")]
c = [x * y for x, y in zip(a, b)]

答案 1 :(得分:0)

使用for循环并追加

list_c = []
for a, b in zip(list_a, list_b):
    list_c.append(a*b)

现在还是一样,只是使用更紧凑的列表理解语法

list_c = [a*b for a, b in zip(list_a, list_b)]

来自iPython

>>> list_a = [1, 2, 3]
>>> list_b = [2, 3, 4]
>>> list_c = [a*b for a, b in zip(list_a, list_b)]
>>> list_c
[2, 6, 12]

zip函数将列表按元素逐个打包:

>>> list(zip(list_a, list_b))
[(1, 2), (2, 3), (3, 4)]

我们使用元组拆包来访问每个元组的元素。

答案 2 :(得分:0)

我提出了两种解决方案。或两者都是Python入门课程所期望的:

#OPTION 1: We use the concatenation operator between lists.
def dot_product_noappend(list_a, list_b):
    list_c = []
    for i in range(len(list_a)):
        list_c = list_c + [list_a[i]*list_b[i]]
    return list_c


print(dot_product_noappend([1,2,3],[4,5,6])) #FUNCTION CALL TO SEE RESULT ON SCREEN



#OPTION 2: we use the append method
def dot_product_append(list_a, list_b):
    list_c = []
    for i in range(len(list_a)):
        list_c.append(list_a[i]*list_b[i])
    return list_c


print(dot_product_append([1,2,3],[4,5,6])) #FUNCTION CALL TO SEE RESULT ON SCREEN

请注意,第一种方法要求您将整数乘积转换为列表,然后才能将其连接到list_c。您可以使用花括号([[list_a[i]*list_b[i]]而不是list_a[i]*list_b[i]来做到这一点。还要注意,在最后一个方法中不需要括号,因为append方法不需要将列表作为参数传递。

我用您提供的值添加了两个函数调用,以便您看到它返回正确的结果。选择最喜欢的功能。

答案 3 :(得分:0)

从获取输入并使用map&lambda函数提供结果。如果您想打印结果之间使用空格(而不是列表),请使用最后一行

list1, list2 = [], []
list1 = list(map(int, input().rstrip().split()))
list2 = list(map(int, input().rstrip().split()))
result_list = list(map(lambda x,y : x*y, list1, list2))
print(*result_list)
相关问题