我一直在Python中进行字典练习,而且我本身对语言和编程本身也很陌生。我一直在尝试使用一个字符串或字符串列表,并让我的代码比较字符串的第一个字母,并将多少个字符串以字母表中的某个字母开头的字典作为字典。这是我到目前为止有:使用字典来计算字符串中的第一个字母 - Python
d = {}
text=["time","after","time"]
# count occurances of character
for w in text:
d[w] = text.count(w)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))
我的目标是什么,是例如得到以下结果:
count_starts(["time","after","time"]) -->{'t': 2, 'a': 1}
但是,什么我越来越更像是以下几点:
count_starts(["time","after","time"]) --> {time:2, after:1}
与我有什么,我已经能够完成它计数整个唯一的字符串出现了多少次,只是不只是字符串中的第一个字母的计数。
我也试过如下:
d = {}
text=["time","after","time"]
# count occurances of character
for w in text:
for l in w[:1]:
d[l] = text.count(l)
# print the result
for k in sorted(d):
print (k + ': ' + str(d[k]))
但所有的给我打印输出是:
{"a":0,"t":0}
我使用Python展台为我的测试目的。
你可以避免特殊用'defaultdict'实现了-case逻辑,实际上'Counter'实现了整数计数器的常见情况。 – smci