繁体   English   中英

如果 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

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

Output

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

我能想到的使用 lambda 的唯一方法是使用mapdict.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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM