【发布时间】:2020-06-23 08:55:38
【问题描述】:
我一直在研究 Al Sweighart 的 Automate the Boring Stuff。我正在努力理解下面的代码:
输入
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print(count)
输出
{'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, 's': 3, 'b': 1, 'r': 5, 'i': 6, 'g': 2, 'h': 3, 'c': 3, 'o': 2, 'l': 3, 'd': 3, 'y': 1, 'n': 4, 'A': 1, 'p': 1, ',': 1, 'e': 5, 'k': 2, '.': 1}
问题
因为在 for 循环中调用什么变量并不重要(即字符可以更改为 x、pie 等),代码如何知道在字符串中的每个字符中运行循环?
【问题讨论】:
-
strings的一个属性是遍历它们会依次生成每个字符。正如你所说,这不是命名变量的问题。
标签: python dictionary for-loop