如果 list-element = dict-key,如何用字典中的值替换 python 列表中的元素?

How to replace elements in python list by values from dictionary if list-element = dict-key?

输入:

[yellow, red, green,  blue]

{green:go, yellow:attention, red:stay}

如何创建新列表:

[attention, stay, go, blue]

有没有办法用 lambda 来实现?

使用dict.get inside a list comprehension:

lst = ["yellow", "red", "green",  "blue"]
dic = {"green":"go", "yellow":"attention", "red":"stay"}
res = [dic.get(e, e) for e in lst]
print(res)

输出

['attention', 'stay', 'go', 'blue']

我能想到的使用 lambda 的唯一方法是使用 map and dict.get:

l = ['yellow', 'red', 'green',  'blue']
d = {'green': 'go', 'yellow': 'attention', 'red': 'stay'}
out = map(lambda x: d.get(x, x), l)
print(list(out))

结果

['attention', 'stay', 'go', 'blue']