我一直在用 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 Visualizer 进行测试。
最佳答案
计算文本中每个项目的第一个字母出现的次数:
from collections import Counter
text = ["time", "after", "time"]
>>> Counter(t[0] for t in text)
Counter({'a': 1, 't': 2})
或者只是获取字典键/值对:
>>> dict(Counter(t[0] for t in text))
{'a': 1, 't': 2}
关于python - 使用字典计算字符串中的第一个字母 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36381020/