错误将一个列表的元素与另一个列表相乘

时间:2019-05-23 20:09:24

标签: python

给出两个整数列表,编写一个函数multLists(list1,list2),该函数将list1的每个值与list2的值相乘,然后返回list1及其更新后的值。

def multLists(list1, list2):
    for i in range(len(list1)):
        list1 = list1[i] * list2[i]
    return list1

length = int(input())
first_list = []
second_list = []
for i in range(length):
    num1 = int(input())
    num2 = int(input())
    first_list.append(num1)
    second_list.append(num2)
list1 = multLists(first_list, second_list)
for i in list1:
    print(i)

提交时会发生以下情况:

2
1
2
3
4
Your output
Traceback (most recent call last):


     File "main.py", line 17, in <module>
    list1 = multLists(first_list, second_list)
  File "main.py", line 3, in multLists
    list1 = list1[i] * list2[i]
TypeError: 'int' object is not subscriptable

Your output does not contain
[8, 24]

1 个答案:

答案 0 :(得分:1)

list1 = list1[i] * list2[i]行中,您将list1(这是一个列表)设置为list1[i] * list2[i](一个数字)的结果。也许您是说list1[i] = list1[i] * list2[i]