重写zip功能将无法正常工作

mad*_*mma 4 python

我正在重写zip函数作为我的Python技能的实践.目的是使用列表理解来编写它,虽然我不是100%确定我完全适应它因此我这样做.

这是我到目前为止:

def zip(l1, l2):
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])

z = zip(['a', 'b', 'c'], [1,2,3])
for i in z: print(i)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误,我不确定如何解决!

Traceback (most recent call last):
  File "path-omitted", line 47, in <module>
    z = zip(['a', 'b', 'c'], [1, 2,3])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

vau*_*tah 7

您的zip函数实现是递归的.在某些时候l1[1:]l2[1:]将变为空,并且尝试访问第一个元素将失败IndexError.

检查两者是否都是非空的,如果是l1,l2则返回空列表:

def zip(l1, l2):
    if not (l1 and l2):
        return []
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
Run Code Online (Sandbox Code Playgroud)

或者你可以抓住IndexError并返回[]:

def zip(l1, l2):
    try:
        return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
    except IndexError:
        return []
Run Code Online (Sandbox Code Playgroud)