【问题标题】:How would I remove words from dictionary key lists that contain 6 or more letters?如何从包含 6 个或更多字母的字典键列表中删除单词?
【发布时间】:2019-05-28 03:04:30
【问题描述】:

我不知道如何创建一个函数,该函数能够从作为字典键值的每个列表中删除少于 6 个字符的单词。

我正在尝试从列表中弹出少于 6 个的每个单词,但我收到“TypeError: cannot unpack non-iterable int object”。我不知道我使用的方法是否正确。

def remove_word(words_dict):
    items_list = list(words_dict.items())

    for key, value in range(len(items_list) -1, -1, -1):
        if len(value) < 6:
            items_list.pop()
    words_dict = items_list.sort()
    return words_dict
words_dict = {'colours' : ['red', 'blue', 'green'],
    'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
    'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                'zebra'],
    }

应该打印:

1.
colours : []
places : ['america', 'malaysia', 'argentina']
animals : ['monkey']

【问题讨论】:

    标签: python


    【解决方案1】:
    # input data
    words_dict = {'colours' : ['red', 'blue', 'green'],
        'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
        'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey',
                    'zebra'],
        }
    # creating a final output dictionary 
    
    #looping through each key value pair present in dictionary and adding the key 
    # the final dictionary and processed valeus to the corresponding key
    # using lambda function, fast readable and easy to understand 
    result = {k:list(filter(lambda x:len(x)>=6, v)) for k,v in words_dict.items()}
    print(result)
    

    输出

        {'colours': [], 'places': ['america', 'malaysia', 'argentina'], 'animals': []}
    

    【讨论】:

      【解决方案2】:

      也许不是最干净的方式,这不是一种有效的方式,但它是可读的,我是这样写的,所以你可以看到它工作的逻辑

       In [23]: def remove_word(my_dict):
          ...:     for key in my_dict:
          ...:         to_delete = []
          ...:         for values in my_dict[key]:
          ...:             if len(values) < 6:
          ...:                 to_delete.append(values)
          ...:         for word in to_delete:
          ...:             my_dict[key].remove(word)
          ...:     return my_dict
          ...:
          ...:
      

      它会给你想要的输出

      In [26]: remove_word(words_dict)
      Out[26]:
      {'colours': [],
       'places': ['america', 'malaysia', 'argentina'],
       'animals': ['monkey']}
      

      【讨论】:

        【解决方案3】:

        {k: [i for i in v if len(i) &gt; 5] for k, v in words_dict.items()}

        【讨论】:

          【解决方案4】:

          您可以使用 dict 上的循环和嵌套理解来做到这一点。

          words_dict = {
              'colours' : ['red', 'blue', 'green'],
              'places' : ['america', 'china', 'malaysia', 'argentina', 'india'],
              'animals' : ['lion', 'cat', 'dog', 'wolf', 'monkey','zebra'],
          }
          
          for key, lst in words_dict.items():
              filtered_lst = [word for word in lst if len(word) >= 6]
              print(f"{key} : {filtered_lst}")
          

          输出如下:

          colours : []
          places : ['america', 'malaysia', 'argentina']
          animals : ['monkey']
          

          或者实际上创建一个函数,该函数基本上删除元素并返回正确的字典,就像您的代码最初所做的那样,然后使用如下内容:

          def remove_words(words_dict):
              return {key: [word for word in lst if len(word) >= 6] 
                      for key, lst in words_dict.items()}
          

          但是你仍然需要循环它们才能正确打印。

          words_dict = remove_words(words_dict)
          for key, lst in words_dict.items():
              print(f"{key} : {lst}")
          

          【讨论】:

            【解决方案5】:

            您可以使用嵌套循环来做到这一点:

            for key in words_dict:
                words_dict[key] = [i for i in dict[key] if len(i) >= 6]
            

            循环理解(根据前一个列表的标准构建一个新列表)实际上是完成此任务的最简单方法,因为 python 如何处理列表迭代器。实际上,您也可以将其放入 dict 理解中:

            new_words_dict = {key: [i for i in value if len(i) >= 6] for key, value in words_dict.items()}
            

            【讨论】:

            • 这行不通,你需要使用words_dict.items() 并且OP 正在弹出项目&lt; 6 所以len(i) 需要&gt;= 6&gt; 5 以遵循他们原来的规定。
            • @Jab 感谢您的更正。相应地进行了编辑。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-06-23
            • 1970-01-01
            • 2015-06-22
            • 2018-06-08
            • 2012-03-15
            • 2019-06-24
            相关资源
            最近更新 更多