python - 使用字典计算字符串中的第一个字母 - Python

标签 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]))

我的目标是获得以下结果:

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/

相关文章:

string - 如何生成用于对相似文本短语进行排序的值?

python - 关于字符串操作的 Python 基础问题 : example: string. 小写

python - 正则表达式在字符串开头未匹配

python - 在python中将元组转换为字典

python - Couchbase 的 Twisted API 不适用于 Python Tornado

python - 使用 python 读取大型文本文件比使用 Matlab 读取相同文本的相同代码慢得多,知道为什么吗?

python - 如何修复运行时错误 : Cannot close a running event loop - Python Discord Bot

java - 迭代 HashMap 的两种方法有什么区别

python - 如何计算对话中每个角色所说的单词数并将计数存储在字典中?

python - 是否存在矩阵乘法的数值最优顺序?