1

我正在尝试编写一个递归函数,它将获取一个数字列表和两个整数 a 和 b,并返回该列表的副本 - 但在此副本中,作为参数给出的数字列表中的所有 a 都将替换为湾。我已经写了这段代码,但是从 shell 运行后,它显示“无”(没有双引号)

def replace(thelist,a,b):
    assert type(thelist)==list, `thelist` + ' is not a list'

    assert type(a)==int, `a` + ' is not an integer'

    assert type(b)==int, `b` + ' is not an integer'
    if len(thelist)==0:
        return []
    return ([b] if thelist[0]==a else [thelist[0]]).append(replace(thelist[1:],a,b))
4

3 回答 3

2
def replace(lst, a, b):
    if not lst:
        return []
    head, tail = lst[0], lst[1:]
    return [b if head == a else head] + replace(tail, a, b)
于 2013-11-07T11:48:28.650 回答
1

只需使用“+”而不是 .append。你得到 None 因为例如 [10].append([2]) 返回 None。

def replace(thelist,a,b):

 assert type(thelist)==list, `thelist` + ' is not a list'

 assert type(a)==int, `a` + ' is not an integer'

 assert type(b)==int, `b` + ' is not an integer'
 if len(thelist)==0:
     return []
 return ([b] if thelist[0]==a else [thelist[0]])+replace(thelist[1:],a,b)
于 2013-11-07T12:04:23.883 回答
0
def replace(thelist,a,b):
    # assert stuff...
    if len(thelist)==0: return []
    if thelist[0] == a: r = [b] 
    else: r = [thelist[0]]
    return r + replace(thelist[1:], a, b)

print replace([1,2,3,1,3,4,1,2], 1, 10) 

给出:

[10, 2, 3, 10, 3, 4, 10, 2]
于 2013-11-07T11:35:57.767 回答