Don*_*e B -1 python string integer list
我对编码还是个新手,所以我为这个基本问题道歉。如何添加到两个单独列表的元素?
listOne = [0, 1 , 7, 8]
listTwo = [3, 4, 5, 6]
listThree = []
for i in listOne:
listAdd = (listOne[i] + listTwo[i])
listThree.append(listAdd)
print(listThree)
Run Code Online (Sandbox Code Playgroud)
我希望输出是,[3, 5, 12, 14]但我一直收到一个语法错误说
TypeError: List indices must be integers, not strings.
Run Code Online (Sandbox Code Playgroud)
我认为这可能与我可能是一个字符串有关,所以我把它放在int(i)for 循环之后的第一行,但这没有帮助。
您可以使用该zip()功能。将 更改为+您想要的任何操作。
listOne = [0, 1 , 7, 8]
listTwo = [3, 4, 5, 6]
l = [x + y for x, y in zip(listOne, listTwo)]
print(l)
[3, 5, 12, 14]
Run Code Online (Sandbox Code Playgroud)