【问题标题】:In python I cannot get the right product [duplicate]在 python 中,我无法获得正确的产品 [重复]
【发布时间】:2020-08-29 02:05:41
【问题描述】:
my_list = ["banana", "apple", "cherry"]

var = my_list.remove("apple")

print(var)

当我运行它时,它应该是这样写的

apple

p.s 我是编码新手

【问题讨论】:

  • list.remove() 不返回已删除的元素 - 为什么需要返回,因为您已经知道它删除了哪个元素?你可以使用var = my_list.pop(my_list.index("apple")),但这是额外的步骤。
  • 你为什么期望remove()返回被移除的元素?

标签: python list


【解决方案1】:

在 python 中,列表的删除方法不返回任何内容。如果元素不存在,它将抛出异常。不过不确定您要完成什么。

【讨论】:

    【解决方案2】:

    您可以使用 pop 代替。您必须指定要从中删除的索引。

    my_list = ["banana", "apple", "cherry"]
    
    var = my_list.pop(my_list.index("apple"))
    
    print(var)
    

    【讨论】:

      【解决方案3】:

      这是我在使用 Python 编程时始终建议使用 IDE 的原因之一。 PyCharm 会给出警告“删除不返回值”。

      【讨论】:

        【解决方案4】:

        您可以通过切片或pop()列表中的项目从列表中获取元素

        my_list = ["banana", "apple", "cherry"]
        print(my_list[my_list.index('apple')])
        #apple
        print(my_list.pop(my_list.index('apple')))
        #apple
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-09
          • 1970-01-01
          • 2017-08-28
          • 1970-01-01
          • 1970-01-01
          • 2016-10-15
          • 1970-01-01
          相关资源
          最近更新 更多