以下是一个按照首个字符出现的次数进行计数的代码示例:
def count_first_char(strings):
count_dict = {}
for string in strings:
first_char = string[0]
if first_char in count_dict:
count_dict[first_char] += 1
else:
count_dict[first_char] = 1
return count_dict
strings = ['apple', 'banana', 'cat', 'dog', 'elephant', 'apple', 'fish']
result = count_first_char(strings)
print(result)
输出结果为:
{'a': 2, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1}
该示例中,我们定义了一个函数count_first_char
,该函数接受一个字符串列表作为参数。然后,我们创建了一个空字典count_dict
,用于存储每个首字母的计数结果。
接下来,我们使用for
循环遍历字符串列表中的每个字符串。对于每个字符串,我们提取出第一个字符,并将其存储在first_char
变量中。
然后,我们通过判断first_char
是否已经在count_dict
中存在来更新计数。如果first_char
已经存在于count_dict
中,则将其对应的值加1;否则,我们将first_char
作为键,将值设置为1。
最后,我们返回计数结果count_dict
。在示例中,输出结果为每个首字母出现的次数。