你如何加入int并列在一起?

时间:2014-11-12 19:23:39

标签: python tail-recursion

但我仍然无法在互联网上的任何其他地方找到加入功能。主要问题是head(items)是int和tail(items)是list,我不能将head和tail组合在一起。这是我试过的代码:

def head(items):  
    return items[0]  
def tail(items):
    return items[1:]  
def isEven(x):  
     return x % 2 == 0  
def extractEvens(items):  
    if (items == None):  
        return None  
    elif (isEven(head(items))):  
        return join(head(items),extractEvens(tail(items)))  
    else:  
        return extractEvens(tail(items)) 



a = [4,2,5,2,7,0,8,3,7]  
print(extractEvens(a))  

以下是我尝试研究的页面的链接:这是过滤模式的代码: link_of_code

4 个答案:

答案 0 :(得分:1)

你也可以试试insert,因为头必须在起点时才更有用。

l = extractEvens(tail(items))
l.insert(0,head(items))
return l

答案 1 :(得分:0)

请提供所需输出的示例。

如果您要创建新的list,将列表与int合并,则应为:

return [head(items)] + tail(items)

答案 2 :(得分:0)

您需要的是append

>>> a=6
>>> b=[1,2,3,4]
>>> b.append(a)
>>> b
[1, 2, 3, 4, 6]

这里你不能连接list和int:

>>> a=6
>>> b=[1,2,3,4]
>>> a+b
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
>>> list(a)+b
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

但是如果你str,它将连接为str而不是int

>>> list(str(a))+b
['6', 1, 2, 3, 4]

答案 3 :(得分:0)

您的代码中存在多个错误:

def isEven(x):
    return x % 2 == 0 # x % 2 not x % ==


def extractEvens(items):
    if not items:
        return [] # return empty list not None
    elif isEven(head(items)):
         # convert ints to strings and put head(items) in a list 
        return "".join(map(str,[head(items)]) + map(str,extractEvens(tail(items)))) 
    else:
        return extractEvens(tail(items))

您也可以在单个列表理解中执行此操作:

a = [4, 2, 5, 2, 7, 0, 8, 3, 7]
print("".join([str(x) for x in a if not x % 2]))