Python - 此函数中的变量如何通过字典进行处理?

Python - how does a variable from this function progress through a dictionary?

我无法理解下面代码的一部分。我能够在在线课程中得到正确的答案,所以我没有寻求帮助来完成它,只是理解了这一点:在最后一段代码中,我对 xfood 工作。 x 如何遍历价格中的项目?

shopping_list = ["banana", "orange", "apple"]

stock = {
  "banana": 6,
  "apple": 0,
  "orange": 32,
  "pear": 15
}

prices = {
  "banana": 4,
  "apple": 2,
  "orange": 1.5,
  "pear": 3
}

def compute_bill(food):
  total = 0
  for x in food:
    total = total + prices[x]
  return total

Python dictionaries(和其他 python 数据结构)实现所谓的 iterator pattern,它一次取一个项目,按顺序,直到它遍历整个数据结构。

Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write

for k in dict: ...

which is equivalent to, but much faster than

for k in dict.keys(): ...

as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

代码:for x in food: 只是在 python dict 中初始化 iterator 并重复调用它以获取下一项直到最后一项。

这就是它在 python(以及其他语言)中的工作方式。 Python 在内部知道 dict 实现了一个 iteratorfor 循环,在下面调用这个迭代器。

prices 是一个字典,键(香蕉、苹果...)到值(4、2、...)的映射。

for x in food表示"For every item in the provided list called food, give it a temporary variable assignment x and do something with x."

total = total + prices[x] 表示 "Assign the current value of total added to the price of item x (looked up from prices)"。对于 food 中的第一项(在本例中为香蕉),您正在寻找 prices 中的相应价格(即 4)。所以,您实际上是在说 total = 0 + 4,然后转到 food 中的下一项。由于 total 现在设置为 4,因此您的分配变为 total = 4 + price['orange']4 + 1.5。完全迭代列表后,您将得到一个 total 总和(在您的示例中为 7.5)。