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

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]