[英]Given the pandas dataframe column, how to replace elements X in a nested list with the values in dictionary if X is a key in a dictionary?
[英]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.