在Python中添加两个列表
我正在尝试将两个列表添加在一起,以便将一个列表的第一项添加到另一个列表的第一项,第二个添加到第二个,依此类推,以形成一个新列表。
目前我有:
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)
输入两个列表后,其中一个是整数列表,另一个是字符串列表,我收到类型错误“无法合并 'str' 和 'int' 对象”。
我尝试使用以下方法将两个列表转换为字符串:
list = [str(a[i]) + str(b[i]) for i in range(len(a))]
但是输入后:
a = ['a','b','c','d']
b = [1,2,3,4]
我得到的输出为:
['a1','b2','c3','d4']
而不是我想要的:
['a+1','b+2','c+3','d+4']
有人有任何建议吗至于我做错了什么?
注意,我必须编写一个基本上与 zip(a,b) 执行相同的函数,但不允许我在函数中的任何地方使用 zip() 。
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.
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']
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?
N.B. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
先压缩,然后添加(但不是)。
Zip first, then add (only not).
你应该做什么
你应该使用
list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
而不是
在您的版本中,您从未说过您希望输出中的加号字符位于两个元素之间。这是你的错误。
示例输出:
What you should do
You should use
list = [str(a[i]) +"+"+ str(b[i]) for i in range(len(a))]
instead of
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: