【问题标题】:Why I can't delete vaules in enumerated list?为什么我不能删除枚举列表中的值?
【发布时间】:2022-01-24 15:24:38
【问题描述】:

我想使用 remove 删除这些元组,但我不能。 我应该如何删除列表中的值?(类似 ["a","b,","c"] 的列表)

def delsong(self):
    value=enumerate(self.songlist)
    for i in value:
        print(i)
    print("which song you will delete: ")

    x=int(input(""))
    value.remove(x)

    pass

【问题讨论】:

  • 你能澄清一下你指的是什么元组吗?您已经提供了一个字符串列表。

标签: python list tuples enumerate


【解决方案1】:

value 是一个迭代器,而不是列表本身。您需要从 self.songlist 中删除该项目。

由于您希望用户输入索引号,因此您需要使用self.songlist.pop(x)。 remove() 方法根据它的值(而不是它的索引)删除一个项目

【讨论】:

    【解决方案2】:

    因为不是list,所以你可能想做的是self.songlist.pop(x)

    【讨论】:

      【解决方案3】:

      你应该直接用list.pop从列表中删除一个项目:

      def delsong(self):
          for i in enumerate(self.songlist):
              # This prints the (index, value) pair as a tuple, is that what you intended?
              print(i)
          print("which song you will delete: ")
      
          self.songlist.pop(int(input("")))
      

      请注意,除了发送中断或提供无效索引之外,您无法为用户提供取消的方式,并且负索引是有效的,但会倒数。例如,如果用户输入-1,它将删除列表中的最后一首歌曲。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-25
        • 2016-07-21
        • 1970-01-01
        • 2012-05-04
        相关资源
        最近更新 更多