簡體   English   中英

如何在列表上迭代字典並在列表中獲取值作為結果

[英]How can I iterate a dictionary over a list and get values as result in list

我無法進行准確的查詢,但這是我想要遍歷列表並找到元素的值並將結果存儲在列表中的參考。

# dict and list are already given to us, we need to iterate over list and check for the elements as key and append the values in a list.

dict = {"a":"apple", "b":"ball"}

list = ["a", "a", "b"]

#output need to be like:
["apple","apple","ball"]

使用 for 循環遍歷列表,然后只需 append 將每個元素的字典值復制到其他列表

d = {"a":"apple","b":"ball"}

l = ["a","a","b"]

output = []

for i in l:
    output.append(d[i])

print(output)

進行迭代並訪問每次迭代的字典鍵的非常快速的方法

result = []
for x in list:
    result.append(dict[x])
print(result)

或者

result = [dict[x] for x in list]

查看 pythonhttps://www.w3schools.com/python/python_lists_comprehension.asp中的列表理解

[dict[i] for i in list]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM