在Python中添加两个列表

发布于 2024-12-13 05:46:27 字数 798 浏览 1 评论 0原文

我正在尝试将两个列表添加在一起,以便将一个列表的第一项添加到另一个列表的第一项,第二个添加到第二个,依此类推,以形成一个新列表。

目前我有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

美人如玉 2024-12-20 05:46:27

先压缩,然后添加(但不是)。

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

Zip first, then add (only not).

['%s+%s' % x for x in zip(a, b)]
如梦 2024-12-20 05:46:27

你应该做什么

你应该使用

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

而不是

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

在您的版本中,您从未说过您希望输出中的加号字符位于两个元素之间。这是你的错误。

示例输出:

>>> 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']

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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文