2016-04-03 64 views
2

我一直在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展台为我的测试目的。

回答

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} 
>>> 
+0

你可以避免特殊用'defaultdict'实现了-case逻辑,实际上'Counter'实现了整数计数器的常见情况。 – smci

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} 
相关问题