【问题标题】:How do I pop() from a list without using pop()?如何在不使用 pop() 的情况下从列表中弹出()?
【发布时间】: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


【解决方案1】:

这里有一些不使用 list 函数的列表中弹出项目的变体,只使用切片和列表理解

使用切片和切片分配弹出最后一项:

def pop_item(lst):
    lst[:] = lst[:-1]

通过重建列表和切片分配弹出一个有价值的项目(最后一个,但可以是参数)

def pop_item(lst):
    lst[:] = [x for x in lst if x!=lst[-1]]

(如果它们具有相同的值,可以弹出列表中的其他项目)

通过指定列表中的项目位置/索引:

def pop_item(lst,item_position):
    lst[:] = [x for i,x in enumerate(lst) if i!=item_position]

【讨论】:

  • 不是所有的英雄都穿斗篷!谢谢琼!
  • 但我穿披风!
  • 它不会在循环中工作,假设我有另一个名为 empty 的函数,它检查列表是否为空,def empty(lst): return lst == [],我尝试做 pop在while循环中直到它为空,它不会工作。
  • 如果它是空的,那么与[] 比较有效。在调用empty 之前打印列表。顺便说一句:bool(lst) 可以更好地检查是否为空
  • 所以假设我有,虽然不是空的(todo):print(remove_item(todo),它会打印列表中的第一个项目,然后打印一个空列表,我将如何解决这个问题?
猜你喜欢
  • 2012-02-29
  • 2021-09-08
  • 1970-01-01
  • 2011-09-05
  • 2015-12-22
  • 2022-10-13
  • 2018-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多