无法在Python中插入(无与空列表)

blu*_*hai 1 python insert nonetype

我正在尝试从Google的Python类中解决以下练习.

E.给定按递增顺序排序的两个列表,按排序顺序创建并返回所有元素的合并列表.您可以修改传入的列表.理想情况下,解决方案应该在"线性"时间内工作,对两个列表进行单次传递.

我正在使用以下Scheme方法(我希望我有汽车,cdr和缺点!).

def helper(list1, list2, result):
  if list1 == None:
    return result + list2
  elif list2 == None:
    return result + list1
  elif list1[0] < list2[0]:
    return helper(list1[1:], list2, result.insert(0, list1[0]))
  else:
    return helper(list1, list2[1:], result.insert(0, list2[0]))

def linear_merge(list1, list2):
  helper(list1, list2, [])
Run Code Online (Sandbox Code Playgroud)

我得到的错误是,当结果为[]时,我似乎无法在结果中插入元素:

AttributeError: 'NoneType' object has no attribute 'insert'
Run Code Online (Sandbox Code Playgroud)

但这在控制台中运行良好:

>>> b = []
[]
>>> b.insert(0, 4)
>>> b
[4]
Run Code Online (Sandbox Code Playgroud)

我是Python的新手,所以我有两个问题:

  1. 关于None vs. []我错过了什么,以及如何让这段代码工作?
  2. 如果Python不适用于Scheme/Lisp方法,那么解决这个问题的"Python方式"是什么?这对我来说不那么重要,因为我可以查看解决方案.

谢谢!

che*_*ner 5

list.insert 返回None,不是修改后的列表.

这需要helper更改为读取

def helper(list1, list2, result):
  if not list1:
    return result + list2
  elif not list2:
    return result + list1
  elif list1[0] < list2[0]:
    return helper(list1[1:], list2, result + [list1[0]])
  else:
    return helper(list1, list2[1:], result + [list2[0]])
Run Code Online (Sandbox Code Playgroud)

请注意两个基本案例的更改.None和空列表[]不是一回事.测试列表是否为空的pythonic方法是将列表视为布尔值:空列表是False其他所有列表True.


正如其他人在我之前注意到的那样,你需要明确地返回helperin 的返回值linear_merge.