2

我打算做什么:

实现一个名为 my_pop() 的函数,它类似于 list pop() 方法。将列表作为输入,从列表中删除最后一个对象并将其返回。

我想出了什么:

# take an input of list;
# if not last item(determined by comparing index number): loop through the list and copy every item to new list
# if last item: pass

def my_pop(l):
    new = []
    l = list(l)
    for i in l:
        if l.index(i) == -1:
            pass
        else:
            new.append(i)
    return new

问题:运行时,它将列表new作为旧列表的精确副本返回l,未能删除l;的最后一项 我一直无法弄清楚为什么我的方法行不通。一般指点不胜感激!谢谢你。

解决方案: 感谢下面的优秀答案,我明白了为什么if l.index(i) == -1不起作用;此处粘贴的是基于 @jh314 洞察力的类似解决方案,但使用了 while 循环:

# take an input of list;
# compare the index using c to determine if it's the last element in the list;

def pop(l):
    n = []
    l = list(l)
    c = 0
    while c < int(len(l)-1):
        n.append(l[c])
        c = c + 1
    else:
        pass

    return n
4

3 回答 3

2

您的问题是最后一个元素的索引( l.index(i) 的结果,其中 i 是列表的最后一个元素)不等于-1。

这是一个潜在的修复:

def my_pop(l):
    new = []
    l = list(l)
    for i in l:
        if l[-1] == i:
            pass
        else:
            new.append(i)
    return new

甚至更好:

def my_pop(l):
    return l[:-1]
于 2013-06-21T21:15:39.340 回答
1

您的代码存在一些问题:

  1. pop函数返回的不是新列表,而是旧列表的最后一个元素 - 看起来您的函数正在返回新列表。
  2. index 函数总是返回一个正索引——记住为什么你可以访问列表的最后一个元素为 -1,它的真正索引是len(l)-1. 此外,如果最后一个元素与列表中的另一个元素相同,会发生什么?

    [1,2,3,1].index(1)

    你认为这个表达式的结果是什么?哎呀!

  3. 我说的是“旧”列表和“新”列表,但它们实际上是同一个列表!您的代码返回列表的修改副本,但旧列表保持不变。您可以通过使用类似的东西来解决这个问题del,它会就地修改列表。

于 2013-06-21T21:22:54.530 回答
0
    def my_pop(lst):
        if len(lst) <= 1 : # "if last item: pass"
            return
        last_item_in_list = lst[-1] # that is what we want to return 
        del lst[-1] 
        # deletes an an item from a list 
        # (see http://docs.python.org/2/tutorial/datastructures.html#the-del-statement )
        #
        return last_item_in_list
于 2013-06-21T23:28:03.073 回答