Nic*_*ick 2 python string dictionary letter
我一直在用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]))
Run Code Online (Sandbox Code Playgroud)
我的目标是,例如得到以下结果:
count_starts(["time","after","time"]) -->{'t': 2, 'a': 1}
Run Code Online (Sandbox Code Playgroud)
但是,我得到的更像是以下内容:
count_starts(["time","after","time"]) --> {time:2, after:1}
Run Code Online (Sandbox Code Playgroud)
凭借我所拥有的,我已经能够计算出一个完整的唯一字符串出现的次数,而不是计算字符串中的第一个字母.
我也尝试过以下方法:
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]))
Run Code Online (Sandbox Code Playgroud)
但是所有在打印输出中给我的是:
{"a":0,"t":0}
Run Code Online (Sandbox Code Playgroud)
我正在使用Python Visualizer进行测试.
要计算文本中每个项目的第一个字母的出现次数:
from collections import Counter
text = ["time", "after", "time"]
>>> Counter(t[0] for t in text)
Counter({'a': 1, 't': 2})
Run Code Online (Sandbox Code Playgroud)
或只是获取字典键/值对:
>>> dict(Counter(t[0] for t in text))
{'a': 1, 't': 2}
Run Code Online (Sandbox Code Playgroud)