我不知道如何创建一个函数,能够从每个字典键的值列表中删除少于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']
发布于 2019-05-28 03:16:32
也许不是最干净的方式,这不是一种有效的方式,但它是可读的,我以这种方式编写它,这样您就可以看到它工作的逻辑
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']}
发布于 2019-05-28 03:31:09
# 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': []}
发布于 2019-05-28 03:12:23
您可以使用嵌套循环来完成此操作:
for key in words_dict:
words_dict[key] = [i for i in dict[key] if len(i) >= 6]
循环理解(基于先前列表的标准构建新列表)实际上是完成此任务的最简单方法,因为python处理列表迭代器的方式。你也可以把它放在字典的理解中:
new_words_dict = {key: [i for i in value if len(i) >= 6] for key, value in words_dict.items()}
https://stackoverflow.com/questions/56334471
复制