繁体   English   中英

如果键匹配,如何用字典的值替换嵌套列表的元素?

[英]How to replace an element of a nested list by the values of a dictionary, if the key matches?

我有一个清单:

lst = [[1,0],[20,0],[21,1],[22,3],[24,2]]

还有一个字典

dct = {0:"Balco",1:"Greg",2:"Palm",3:"New"}

我想用字典中匹配的值替换嵌套列表的第二个元素。

因此,预期的新列表将是:

lst = [[1,"Balco"],[20,"Balco"],[21,"Greg"],[22,"New"],[24,"Palm"]]

一个简单的for循环应该可以工作:

for item in lst:
    item[1] = dct[item[1]]

print(lst)

或者,对单行使用列表理解:

result = [[item[0], dct[item[1]]] for item in lst]

暂无
暂无

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

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