我正在创建一个程序,在两个单独的列表中添加相同基数的元素:
list1 = [1,2,3]
list2 = [2,3,4]
Run Code Online (Sandbox Code Playgroud)
这样list3就可以了[3,5,7]
这是我的代码:
def add_list(lst1,lst2):
sum_lst = []
index = 0
while (len(lst1)-1) >= index:
sum_lst[index] == lst1[index] + lst2[index]
index += 1
return sum_lst
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到此错误"索引超出范围":
sum_lst[index] == lst1[index] + lst2[index]
Run Code Online (Sandbox Code Playgroud)
考虑到我在超过列表长度之前停止索引,它是如何超出范围的?
sum_lst[index] == lst1[index] + lst2[index]
^1 ^2
Run Code Online (Sandbox Code Playgroud)
2个主要问题:
==是不一样的=.==是一个布尔表达式操作,它评估相等性,而=它是赋值运算符.两个修复:
#replaces that one line
sum_lst.append(lst1[index]+lst2[index])
Run Code Online (Sandbox Code Playgroud)
要么
#replaces the whole function
sum_lst = [x+y for x,y in zip(lst1,lst2)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
774 次 |
| 最近记录: |