如何在python中添加两个具有相同索引数量的列表 [英] How to add two lists with the same amount of index's in python

查看:364
本文介绍了如何在python中添加两个具有相同索引数量的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还是编码新手,因此我对基本问题深表歉意.如何添加到两个单独列表的元素?

I am still new to coding so i apologize for the basic question. How do I add to elements of two seperate lists?

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)

我希望输出为[3, 5, 12, 14],但我不断收到语法错误,提示

I want the output to be [3, 5, 12, 14] but i keep getting a syntax error saying

TypeError: List indices must be integers, not strings. 

我认为这可能与我可能是一个字符串有关,因此我将int(i)作为for循环后的第一行,但这没有帮助.

I thought this may have to do with i possibly being a string so i put int(i) as the first line after the for loop but this did not help.

推荐答案

您可以使用zip()函数.将+更改为所需的任何操作.

You can use the zip() function. Change the + to whatever operation you want.

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]

这篇关于如何在python中添加两个具有相同索引数量的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆