我打算做什么:
实现一个名为 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