python - 如何将dict与python中的列表进行比较
问题描述
假设我们有这些dict
和list
:
dict = {"a": 20, "b": 3, "c": 50}
list = ["a", "z", "d", "c"]
我需要一种方法来获得下面的输出,如下所示:只有当键在列表中时,dict 中键的值才会被求和:
70
a c
这样做的方法是什么?我认为是if
或else
比较,但我的知识延伸到这里。
解决方案
简单易懂的替代方案:
dict = {"a": 20, "b": 3, "c": 50}
# this creates your dictionary
list = ["a", "z", "d", "c"]
# this creates your list
finalAnswerNumber = 0
# this variable will become "70" in your example
finalAnswerKeys = ""
# This variable is what would output "a" and "c" in your example
for stuff in list:
# This for statement creates a "stuff" for every element of the list
if stuff in dict:
# This if statement checks if "stuff" is a key in dict
finalAnswerNumber+=dict[stuff]
# This adds the value for the key "stuff" to the variable finalAnswerNumver, it breaks is the value is a not a number
finalAnswerKeys+=stuff+" "
# This adds the "stuff" and a space to the variable finalAnswerKeys
print(finalAnswerNumber)
# The following print functions aren't necessary if you would prefer not to print the values
# this prints the number (in this case 70)
print(finalAnswerKeys)
# this posts the keys (in this case "a" and "c")
运行此代码后的输出应如下所示
70
a c
推荐阅读
- c - 无法第二次重新分配信号处理程序
- android - 如何防止片段中的android listview重复?
- python - 如何创建以下循环以获取 CDO 的票面利率
- r - 使用`proportionBF`进行单样本比例检验(两级以上)
- android - 错误:无法解决:com.android 尝试添加多个依赖项时
- javascript - ant vue如何实现表格的升序或降序?
- linux - 如何记录正在运行的进程的实时输出
- javascript - How to determine whether the browser process runs in foreground?
- php - how to recompile smarty template after edit of template files?
- android - 有没有办法在单击按钮时使列表视图与幻灯片动画一起出现?