我一直在用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进行测试。
答案 0 :(得分:6)
计算文本中每个项目的第一个字母的出现次数:
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}
答案 1 :(得分:2)
d = {}
text = ['time', 'after', 'time']
for w in text:
if w: # If we have the empty string. w[0] Does not Exist (DNE)
if w[0] in d: # Check to see if we have first character in dictionary.
d[w[0]] = d[w[0]] + 1 # Use the first character as key to dictionary.
else: # If character has not been found start counting.
d[w[0]] = 1 # Use the first character as key to dictionary.
使用Python的IDLE我得到:
>>> d = {}
>>> text = ['time', 'after', 'time']
>>> for w in text:
if w:
if w[0] in d:
d[w[0]] = d[w[0]] + 1
else:
d[w[0]] = 1
>>> print d
{'a': 1, 't': 2}
>>>