0

我正在尝试在列表中查找订单号,例如:

lst = [ a, b, [c,d], e, f]

order([c,d]) = 2
order('e') = 3

我是这样想的:

def order(item,lst):
    if lst[0] == item:
       return n
    else:
       return order(item,lst[0:])

但它给出了错误(相关的递归深度)。我的错是什么?或者我该怎么做?

4

4 回答 4

6

为什么不直接使用.index()

In [1]: l = [ a, b, [c,d], e, f]
In [2]: l.index([c,d])
Out[2]: 2
In [4]: l.index(e)
Out[4]: 3

如果您确实需要递归函数,请使用以下内容:

def order(item, l, n=0):
    if l:
        if l[0] == item:
            return n
        elif len(l) >= 2: # for python 2, use "else:"
            return order(item, l[1:], n+1)

如果递归不是必须的,但你不能使用.index(),请使用 for 循环:

def order(item, l):
    for i,v in enumrate(l):
        if v == item:
            return i

使用这两种方法,只需调用order([c,d], lst)

于 2013-01-20T12:26:18.093 回答
1
  1. 您的函数在基本情况下返回 n,但从不为其分配任何内容。如果你要找的东西在第一个元素中,它应该返回 0。
  2. 您的递归案例通过了整个列表,这就是递归永远不会结束的原因。如果您传递了 lst[1:],那么每次调用时列表都会变小,但您需要将结果加 1(实际上,在每次递归调用中,所有内容都会下移 1 个位置)。
于 2013-01-20T12:15:46.350 回答
1
def order(item, lst,n=0):
    if not lst:
        return None
    elif lst[0] == item:
        return n
    else:
        return order(item, lst[1:],n+1)

lst = ['a', 'b', ['c', 'd'], 'e', 'f']

order(['c', 'd'], lst)

出去:

2
于 2013-01-20T12:23:49.437 回答
-1

Python 有一个内置函数可以做到这一点:

lst = ['a', 'b', ['c', 'd'], 'e', 'f']

assert lst.index(['c', 'd']) == 2
assert lst.index('e') == 3

如果要修复自己的功能,则需要一个基本案例:

def order(item, lst):
    if not lst:
        return None
    elif lst[0] == item:
        return n  # You need to calculate n here. 
                  # I'm not doing your homework for you
    else:
        return order(item, lst[1:])
于 2013-01-20T12:08:30.163 回答