简体   繁体   English

int 对象不可迭代添加两个列表

[英]int object is not iterable adding two lists

The aim is to add two given lists through recursion.目的是通过递归添加两个给定的列表。 For example例如

[1,2,3] + [4,5,6] = [5,7,9]

I am getting an我得到一个

int object is not iterable

error.错误。

Here is the code:这是代码:

def seqaddr(l1,l2):
    if len(l1)==1:
        l1[0]=l1[0]+l2[0]
        return l1
    else:
        return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + list(l1.pop()+l2.pop())

seqaddr([1,2,3],[4,5,6])

You can't convert an number to a list using list(n) .您不能使用list(n)将数字转换为列表。 You should use a list literal.您应该使用列表文字。 Change the following line:更改以下行:

return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + list(l1.pop()+l2.pop())

to

return seqaddr(l1[:len(l1)-1],l2[:len(l2)-1]) + [l1.pop() + l2.pop()]

Update: Your function mutates the original arguments, which is generally considered a Bad Thing™.更新:您的函数改变了原始参数,这通常被认为是 Bad Thing™。 An idempotent version can be written as:幂等版本可以写成:

def seqaddr(l1, l2):
    if len(l1) == 1:
        return [l1[0] + l2[0]]
    else:
        return seqaddr(l1[:-1], l2[:-1]) + [l1[-1] + l2[-1]]

A further simplification to the last line of code in the answer by Selcuk Selcuk 对答案中最后一行代码的进一步简化

def seqaddr(l1,l2):
if len(l1)==1:
    l1[0]=l1[0]+l2[0]
    return l1
else:
    return seqaddr(l1[:-1],l2[:-1]) + [l1.pop() + l2.pop()]

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

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