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")
d = {"a": 20, "b": 3, "c": 50}
l = ["a", "z", "d", "c"]
val_sum = sum(v for k,v in d.items() if k in l) # 70
keys = ' '.join(k for k,v in d.items() if k in l) # 'a c'
简单易懂的备选方案:
运行此代码后的输出应该如下所示
备选方案:
查找列表
l
和dictd
键之间的并集。输出为{a, c}
(<;-这是一个集合)。通过列表理解,在求和之前获取索引值:相关问题 更多 >
编程相关推荐