不确定如何制作计数器

Not Sure How To Make A Counter

我有一个 python 作业,我卡在了第 7 步。我该如何解决这一步?它涉及计算某个项目在列表中出现的次数。

Link to assignment

  1. Count how many of each alphabetic character.

使用 dictionary:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

例如{"Key1" : "Value 1", 1 : 2, "Key3" : 4, 5 : "Value5"}

在这种情况下,为了计数,我们可以将字典设置成这样: {character : # of times it has shown up} 例如 {"a" : 7, "b" : 29}

我们如何使用字典作为计数器?嗯,你看,他们有这个很酷的功能。如果 KeyValueint()float(),您可以像使用 int 或 float 一样使用它!

>>> example = {'letter' : 13}
>>> example['letter'] += 10
>>> example['letter'] 
23
>>> example['letter'] *= 1.02
>>> example['letter']
23.46

知道了这一点,我们可以遍历列表或段落中的所有字母,然后将它们添加到字典并将它们的值设置为 1(如果尚未添加)或者,如果已添加,只是 += 1 他们的价值。