【发布时间】:2017-11-17 19:21:51
【问题描述】:
我有一个名为 pop_item() 的函数,我试图让它像 pop() 一样与列表类一起使用,我该怎么做,这是我的代码: 默认空(lst): 返回 lst == []
def pop_item(lst):
lst = lst[::-1]
new_lst = []
for i in lst:
if i != lst[-1]:
new_lst += [i]
lst = new_lst
return lst
def main():
todo = [1,2,3,4]
print(todo) #prints [1,2,3,4] as expected
print('\n' + 75 * '_' + '\n')
print(pop_item(todo)) #pop the item off
print(todo) #output should then be [1,2,3]
if __name__ == '__main__':
main()
注意:我不允许使用任何内置函数,例如 len()、index、del() 等。
【问题讨论】:
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。 “这是我的代码”不是问题规范。
-
查看这个可爱的debug 博客寻求帮助。
-
试试
[x for x in todo if x!=todo[-1]] -
试试 [x for x in todo if x == todo[-1]] 怎么样? @Jean-FrançoisFabre
-
你可以使用 slice 吗?
标签: python python-3.x