【问题标题】:How can I iterate a dictionary over a list and get values as result in list如何在列表上迭代字典并在列表中获取值作为结果
【发布时间】:2021-02-24 14:36:07
【问题描述】:

我无法准确查询,但这是我想要遍历列表并找到元素值并将结果存储在列表中的参考。

# 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"]

【问题讨论】:

  • 避免命名变量dictlist,因为它们是内置的

标签: python list loops dictionary


【解决方案1】:

使用 for 循环遍历列表,然后将每个元素的字典值附加到其他列表中

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

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

output = []

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

print(output)

【讨论】:

  • 列表理解有助于提高可读性。
【解决方案2】:

进行迭代并访问每次迭代的字典键的非常快速的方法

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

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

【讨论】:

    【解决方案3】:

    查看 python https://www.w3schools.com/python/python_lists_comprehension.asp 中的列表推导

    [dict[i] for i in list]
    

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 2023-01-02
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 2022-12-01
      相关资源
      最近更新 更多