【问题标题】:How to remove an element from a list by user input in python?如何通过python中的用户输入从列表中删除元素?
【发布时间】:2014-01-31 12:25:13
【问题描述】:

我想使用用户输入和 for 循环从列表中删除一个元素。

这是我得到的:

patientname = input("Enter the name of the patient: ") 
for x in speclistpatient_peter:                
    del speclistpatient_peter

【问题讨论】:

  • 大概speclistpatient_peter是一个名字列表,全是字符串?

标签: python list for-loop user-input


【解决方案1】:

只需对列表使用remove 方法:

 l = ["ab", "bc", "ef"]
 l.remove("bc")

l 中删除元素"bc"

【讨论】:

    【解决方案2】:

    使用列表推导;在循环时更改 for 循环中的列表可能会导致列表大小发生变化和索引向上移动时出现问题:

    speclistpatient_peter = [x for x in speclistpatient_peter if x != patientname]
    

    这会重建列表,但会忽略与输入的 patientname 值匹配的元素。

    【讨论】:

      【解决方案3】:

      此行不正确:

      patientname = input("Enter the name of the patient: ") 
      

      将任何内容放入input() 函数中而不是您要从列表中删除或查找的特定内容将导致错误。在您的情况下,您添加了("Enter the name of the patient: "),因此在执行后它将在列表中搜索“输入患者姓名:”,但它不存在。

      以下是从列表中删除特定项目的方法。您没有使用循环,而是可以使用remove() 函数将其删除:

      print("Enter the item you want to delete")
      patientname = input() # Dont Put anything between the first bracket while using input()
      speclistpatient_peter.remove(patientname)
      print(speclistpatient_peter)
      

      【讨论】:

      • 其实不会。 input在python中很特殊,input里面的参数就是提示符。您可以在 IDLE 或任何其他 REPL 中运行它。
      【解决方案4】:

      删除某个元素: speclstpatient_peter.remove('name')


      如果数组包含 2x 相同的元素,而您只想要第一个,这将不起作用。大多数动态只是一个计数器而不是一个指针:

      x=0
      while x<len(speclistpatient_peter):
          if speclistpatient_peter[x].find(something):   # or any if statement  
               del(speclistpatien_peter[x])
          else:
               x=x+1
      

      或者创建一个函数来保持它的可读性:

      def erase(text, filter):
          return [n for n in text if n.find(filter)<0] 
      
      a = ['bart', 'jan']
      print erase(a, 'rt')
      

      【讨论】:

        【解决方案5】:
        print("Enter the item you want to delete")
        patientname = input() # Dont Put anything between the first bracket while using input()
        speclistpatient_peter.remove(patientname)
        print(speclistpatient_peter)
        

        【讨论】:

        • 欢迎来到 StackoverFlow!请尝试标记您的代码并解释您的代码以获取更多详细信息。
        猜你喜欢
        • 1970-01-01
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-11
        • 1970-01-01
        相关资源
        最近更新 更多