小编phr*_*tyl的帖子

削减Python中的列表字典

我正在使用Python中的字谜程序字典.键是排序字母的元组,值是具有这些字母的可能单词的数组:

wordlist = {
   ('d', 'g', 'o'): ['dog', 'god'],
   ('a', 'c', 't'): ['act', 'cat'],
   ('a', 's', 't'): ['sat', 'tas'],
}
Run Code Online (Sandbox Code Playgroud)

我正在使用正则表达式来过滤列表.因此,r't$'作为过滤器,最终结果应为:

filtered_list = {
   ('a', 'c', 't'): ['act', 'cat'],
   ('a', 's', 't'): ['sat'],
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经把它归结为两步了.首先,保留与表达式匹配的所有单词:

tmp = {k: [w for w in v if re.search(r't$', w)] for k, v in wordlist.items()}
Run Code Online (Sandbox Code Playgroud)

这给我留下了空列表:

{
   ('d', 'g', 'o'): [],
   ('a', 'c', 't'): ['act', 'cat'],
   ('a', 's', 't'): ['sat'],
}
Run Code Online (Sandbox Code Playgroud)

然后我需要第二遍来摆脱空列表:

filtered_list = {k: v for k, v in tmp.items() if …
Run Code Online (Sandbox Code Playgroud)

python dictionary list-comprehension dictionary-comprehension

7
推荐指数
1
解决办法
108
查看次数