简体   繁体   English

在Python中添加两个列表

[英]Add two lists in Python

I am trying to add together two lists so the first item of one list is added to the first item of the other list, second to second and so on to form a new list. 我试图将两个列表添加在一起,因此一个列表的第一项添加到另一个列表的第一项,第二项添加到第二项,依此类推以形成新列表。

Currently I have: 目前我有:

def zipper(a,b):
    list = [a[i] + b[i] for i in range(len(a))]
    print 'The combined list of a and b is'
    print list

a = input("\n\nInsert a list:")
b = input("\n\nInsert another list of equal length:")

zipper(a,b)

Upon entering two lists where one is a list of integers and one a list of strings I get the Type Error 'Can not cocanenate 'str' and 'int' objects. 输入两个列表,其中一个是整数列表,一个是字符串列表,我得到类型错误'不能cocanenate'str'和'int'对象。

I have tried converting both lists to strings using: 我尝试使用以下命令将两个列表转换为字符串

list = [str(a[i]) + str(b[i]) for i in range(len(a))]

however upon entering: 但是在进入时:

a = ['a','b','c','d']
b = [1,2,3,4]

I got the output as: 我得到的输出为:

['a1','b2','c3','d4'] [ 'A1', 'B2', 'C3', 'D4']

instead of what I wanted which was: 而不是我想要的是:

['a+1','b+2','c+3','d+4']

Does anyone have any suggestions as to what I am doing wrong? 有没有人对我做错了什么有任何建议?

NB I have to write a function that will essentially perform the same as zip(a,b) but I'm not allowed to use zip() anywhere in the function. 注意我必须编写一个与zip(a,b)基本相同的函数,但我不允许在函数的任何地方使用zip()。

首先压缩,然后添加(仅限不)。

['%s+%s' % x for x in zip(a, b)]

What you should do 你应该做什么

You should use 你应该用

list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]

instead of 代替

list = [str(a[i]) + str(b[i]) for i in range(len(a))]

In your version, you never say that you want the plus character in the output between the two elements. 在您的版本中, 您永远不会说要在两个元素之间的输出中添加加号字符 This is your error. 这是你的错误。

Sample output: 样本输出:

>>> a = [1,2,3]
>>> b = ['a','b','c']
>>> list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
>>> list
['1+a', '2+b', '3+c']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM