【问题标题】:Python - How to use a function to delete any list element that matches the users inputPython - 如何使用函数删除与用户输入匹配的任何列表元素
【发布时间】:2017-05-14 17:59:14
【问题描述】:

基本上我希望用户输入一个数字,然后扫描从 dictionary.txt 导入的列表中的单词。然后它删除任何长度等于用户输入的单词,然后更新函数之外的列表。

def read_and_delete(x):
        count = 0
        i = 0
        for delete in x:
            if x[i] != word_length:
                del x[i]
                i += 1
                return
            elif x[i] == word_length:
                count += 1
                i += 1
                return
            else:
                break
        print(len(list_of_words))

word_length = int(input("Please enter a word length: "))
dictionary = open("dictionary.txt", "r")
list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]
read_and_delete(list_of_words)

【问题讨论】:

    标签: python list function


    【解决方案1】:

    首先,我想回顾一下你已经拥有的功能:

    def read_and_delete(x):
        count = 0
        i = 0
    
        # for each word in list, store word in the "delete" variable
        for delete in x:
    
            # you are iterating over elements, but also using index
            if x[i] != word_length:  # if word not equals length
                del x[i]
                i += 1
                return  # exit from function
    
            elif x[i] == word_length:  # again, comparing a word and a number
                count += 1
                i += 1
                return  # exit from function
            else:  # never happens, because word is either
                   # equal or not, there is no other case
                break  # exit from loop
        # if we actually visited the for loop (the list was not empty),
        # this line would never be executed
        print(len(list_of_words))
    

    接下来,如何解决:

    1. 如果您想遍历 all 列表,则不应使用 return 或 break(认为这些在其他情况下很有用)。
    2. 如果你确实想从列表中删除元素,你应该做的有点不同:How to remove list elements in a for loop in Python?
    3. 要获取单词(和任何其他字符串)的长度,您可以使用len()
    4. 另外,检查条件的逻辑。

    总而言之,这里是固定函数(创建一个新列表):

    def read_and_delete(x):
        result = []
    
        for word in x:
            if len(word) != word_length:
                result.append(word)  # add word to the end of "result"
    
        print(len(result))
    

    如您所见,循环现在非常简单。因此,您可以将其重写为列表推导:

    # instead of function call
    filtered_list = [word for word in list_of_words if len(word) != word_length]
    print(len(filtered_list))
    

    你可以这样理解:

    [word                          # put each "word" into a list
     for word in list_of_words     # get them from "list_of_words"
     if len(word) != word_length]  # leave only those which length != "word_length"
    

    编辑:函数中的固定条件。

    【讨论】:

      【解决方案2】:

      假设您的dictionary.txt 每行列出一个单词:

      word_length = int(input("Please enter a word length: "))
      
      with open("dictionary.txt", "r", encoding="utf-8") as word_list:
          words = [line.strip() for line in word_list if len(line.strip()) != word_length]
      
      print("%i words remain" % len(words))
      print(words)
      

      我们的想法不是创建一个列表,然后在单独的步骤中从中删除项目,而是在我们构建列表时过滤项目。

      【讨论】:

      • 所有的词都在单独的行上,我应该提一下
      • 所以上面应该可以工作(将来,请始终在您的问题中包含您输入的样本。以这样的方式编写问题,以便某人根本没有上下文有所有必要的信息。)
      【解决方案3】:

      您可以使用内置的“过滤器”功能:

      ls = ['word1','word','w0']
      len_delete = 4
      new_ls = filter(lambda x:len(x)!=len_delete,ls)
      

      new_ls = ['word1', 'w0']

      【讨论】:

      • 甜蜜!奇怪的是,这也有效ls = filter(lambda x:len(x)!=len_delete.ls)我必须看看filter
      • 不是in-place操作,基本上你只是重新声明了变量'ls'
      • ls = ['word1','word','w0'] len_delete = 4 print 'id before: {0}'.format(id(ls)) ls = filter(lambda x:len(x)!=len_delete,ls) print 'id after: {0}'.format(id(ls))
      • 感谢您的证明!
      【解决方案4】:
      def read_and_delete(x):
          resulting_list = []          
          for delete in x:
              if len(delete) == word_length: # len(delete) returns length of element
                  continue  # goes to the next element in the list                             
              else:
                  resulting_list.append(delete)             
          print(resulting_list)
      
      word_length = int(input("Please enter a word length: "))
      dictionary = open("dictionary.txt", "r")
      list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]
      read_and_delete(list_of_words)
      

      附:学习更多关于循环是如何工作的:)

      【讨论】:

      • 为什么在这段代码中使用enumerate?当然for delete in x 会起作用。
      • @RolfofSaxony 你是对的。感谢您的提示。我正在重写原始代码,并且有 'count' 和 'i' 变量。我将其切换为枚举,在其他更改后没有意识到它们不再是不必要的。
      【解决方案5】:

      我的六便士值:

      def read_and_delete(x,word_length):
          x = [elem for elem in x if len(elem) !=word_length]
          return x
      
      a=['123','1234','123','123','abcdef','abc','1234']
      a=read_and_delete(a,3)
      a
      ['1234', 'abcdef', '1234']
      

      对不起@Meloman!刚刚看到你的帖子,我几乎复制了它,而且解释得少得多。

      【讨论】:

        【解决方案6】:

        我认为您来自 C 或类似语言:

        def read_and_delete(x):
            for ix, delete in enumerate(x):
                if len(delete) == word_length:
                    del x[ix]
        
            return x
        
        word_length = int(input("Please enter a word length: "))
        dictionary = open("dictionary.txt", "r")
        list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]
        read_and_delete(list_of_words)
        print(list_of_words)
        

        这个较新版本的代码将就地更新列表,因此在read_and_delete 中对x(传递给函数的列表)所做的任何更改都会影响该列表的所有引用,包括list_of_words。此函数还返回受影响的列表,但是您可以轻松地将其删除,因为 list_of_words 会通过函数内部对其进行的任何更改进行更新。当然,有一种更简单的方法可以在 Python 中实现这一点,为了清楚起见,我使用了您的代码,以免让您感到困惑。

        编辑: 感谢 @RolfofSaxony 指出上述代码中的歧义,因此我编辑了这个问题来解决这个问题:

        word_length = int(input("Please enter a word length: "))
        dictionary = open("dictionary.txt", "r")
        list_of_words = [word.rstrip('\n').rstrip('\r') for word in dictionary]
        
        def read_and_delete(x):
            for delete in x[:]:
                if len(delete) == word_length:
                    ix = x.index(delete)
                    del x[ix]
            return x
        
        
        read_and_delete(list_of_words)
        print(list_of_words)
        

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-05
        • 1970-01-01
        • 1970-01-01
        • 2020-12-05
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        相关资源
        最近更新 更多