【问题标题】:I'd like to remove multiple elements from a list by user input [duplicate]我想通过用户输入从列表中删除多个元素[重复]
【发布时间】:2020-10-30 09:08:09
【问题描述】:

我想在 python 中创建一个脚本,从列表中删除用户插入的多个对象。

我试过了:

list = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
print= ("do you want to remove something?")
removed = input()
list.remove(removed)

但在这样做时,我不能删除多个元素。 有没有办法做到这一点,而且还能够删除两个或更多元素?

【问题讨论】:

    标签: python python-3.x list input


    【解决方案1】:

    您可以使用以下代码:

    mylist =["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
    
    print("do you want to remove something?")
    user_input = input()
    while user_input != "no":
        mylist.remove(user_input)
        for item in mylist:
            print(item, end=" ")
        print("\nanything else?")
        user_input = input()
    

    程序会不断地从用户那里删除字符串,直到用户拒绝为止。

    【讨论】:

      【解决方案2】:

      这是一个简单的基于列表理解的解决方案:

      lst = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
      inp = input("Enter element to remove: ")
      if inp:
          lst = [i for i in lst if i!=inp]
      print(lst)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-16
        • 2015-01-05
        • 2012-05-09
        • 2021-01-12
        相关资源
        最近更新 更多