python - 基于列表理解中的键映射字典值

标签 python

假设我有一个字典,其中的键是我想用于 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/

相关文章:

python - 'Roster_Name = Roster_List[1] IndexError : list index out of range", 列表 "Roster_List"有 3 个元素? - Python

python - 在生产过程中 Django 管理站点会发生什么?

python - 在最近的时间戳上合并两个 Pandas 数据帧

python - 有没有办法简化这段代码?

python - 运行 python 脚本时的一个简单错误

javascript - 是否有一种很好的 AJAX/JQuery 验证表单的方法,可以很好地与 Django 的表单模型配合使用?

python - 将 numpy 字符串数组转换为 base-16 中的整数

python - 如何将可选参数传递给 python 类中的 __init__ 函数

当服务器上的(子)目录在哪里时,Python ftp.nlst()返回空列表

python - 如何在Python中编写一个分割字符串并将其转换为字典的函数