Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从dict值的列表中删除短字符串_Python_String_List_Dictionary - Fatal编程技术网

Python 如何从dict值的列表中删除短字符串

Python 如何从dict值的列表中删除短字符串,python,string,list,dictionary,Python,String,List,Dictionary,我想创建一个名为remove\u short\u synonyms()的函数,该函数传递一个dict 作为一个参数。参数dict的键是words和 相应的值是同义词列表。该函数将删除所有 每个对应列表中少于7个字符的同义词 同义词 如果这是命令: synonyms_dict = {'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']} 如何将其作为输出 {'beautiful':

我想创建一个名为
remove\u short\u synonyms()
的函数,该函数传递一个dict 作为一个参数。参数dict的键是words和 相应的值是同义词列表。该函数将删除所有 每个对应列表中少于7个字符的同义词 同义词

如果这是命令:

synonyms_dict = {'beautiful': ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}
如何将其作为输出

{'beautiful': ['dazzling', 'handsome', 'magnificent', 'splendid']}

运用听写理解和列表理解

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}
synonyms_dict = {k:[v1 for v1 in v if len(v1) >= 7] for k, v in synonyms_dict.items()}
print(synonyms_dict)

# {'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']}

​

假设您有
python>=3.x
,对于初学者来说,一个更具可读性的解决方案是:

synonyms_dict = {'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']}

new_list = []
for key,value in synonyms_dict.items():
   for i in range(len(value)):
      if len(value[i]) >= 7:
         new_list.append(value[i])

synonyms_dict['beautiful'] = new_list
print(synonyms_dict)

我认为你的问题的标题应该是从列表中删除值,而不是dict

可以使用remove、del或pop删除python列表中的元素。

或者以一种更为通灵的方式,我认为

dict['beautiful'] = [item for item in dict['beautiful'] if len(item)>=7]

这是一个修改现有词典而不是替换它的函数。如果您对同一个词典有多个引用,这可能很有用

synonyms_dict = {
    'beautiful' : ['pretty', 'lovely', 'handsome', 'dazzling', 'splendid', 'magnificent']
}

def remove_short_synonyms(d, minlen=7):
    for k, v in d.items():
        d[k] = [word for word in v if len(word) >= minlen]

remove_short_synonyms(synonyms_dict)
print(synonyms_dict)
输出

{'beautiful': ['handsome', 'dazzling', 'splendid', 'magnificent']}

请注意,此代码确实使用新列表替换字典中的现有列表。如果确实需要,可以通过将赋值行更改为

d[k][:] = [word for word in v if len(word) >= minlen]

尽管这会稍微慢一点,而且可能没有理由这样做。

user1190882的答案是dict对象的更通用解决方案,而不仅仅是列表对象
def remove_short_synonyms(self, **kwargs):

dict = {}
  word_list = []

  for key, value in synonyms_dict.items():
    for v in value:
      if len(v) > 7:
        word_list.append(v)
    dict[key] = word_list

  print dict


remove_short_synonyms(synonyms_dict)