假设我有一个字典,其中的键是我想用于 str 搜索的子字符串。我想看看键是否存在于列表的元素中,如果存在,我想将它们设置为等于该键的值,如果没有 str 匹配,则将其设置为“不匹配” .
d = {'jun':'Junior', 'jr':'Junior', 'sr':'Senior', 'sen':'Senior'}
phrases = ['the Jr. title', 'sr jumped across the bridge', 'the man on the moon']
这是我尝试过的方法,但我似乎无法适应列表理解中的“不匹配”语句。帮助表示赞赏。附言。想针对我的特定用例坚持使用字典/列表理解方法
# Tried
[[v for k,v in d.items() if k in str(y).lower()] for y in phrases]
# Output
[['Junior'],['Senior'],[]]
# Desired Output
[['Junior'],['Senior'],['no match']]
最佳答案
只需添加一个 或 ['no match']
即可将空列表(这是错误的)替换为外部列表中的 ['no match']
占位符理解。
>>> d = {'jun':'Junior', 'jr':'Junior', 'sr':'Senior', 'sen':'Senior'}
>>> phrases = ['the Jr. title', 'sr jumped across the bridge', 'the man on the moon']
>>> [[v for k,v in d.items() if k in str(y).lower()] or ['no match'] for y in phrases]
[['Junior'], ['Senior'], ['no match']]
关于python - 基于列表理解中的键映射字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74766520/