此代码计算字母,但我不希望它重写同一个字母两次。我能做些什么?
d=list('banttnay')
for letter in d:
print letter, d.count(letter)
输出:
b 1
a 2
n 2
t 2
t 2
n 2
a 2
y 1
我不希望它重写 'a 2' 或 't 2' 两次
使用set()
:
In [40]: d='banttnay'
In [41]: for x in set(d):
....: print x,d.count(x)
....:
a 2
y 1
b 1
t 2
n 2
OrderedDict
或从collections
模块维护订单使用:
In [67]: from collections import *
In [68]: c=OrderedDict()
In [69]: for x in d:
c[x]=c.get(x,0)+1
In [71]: for x in c:
....: print x,c[x]
....:
b 1
a 2
n 2
t 2
y 1
或者您也可以使用以下unique_everseen
配方itertools Recipes
:
>>> d='banttnay'
>>> from itertools import *
>>> def unique_everseen(iterable, key=None):
... seen = set()
... seen_add = seen.add
... if key is None:
... for element in ifilterfalse(seen.__contains__, iterable):
... seen_add(element)
... yield element
... else:
... for element in iterable:
... k = key(element)
... if k not in seen:
... seen_add(k)
... yield element
...
>>> for x in unique_everseen(d):
... print x,d.count(x)
...
b 1
a 2
n 2
t 2
y 1
然后使用集合 - 它只允许其中的唯一项目:
d = 'banttnay'
for letter in set(d):
print letter, d.count(letter)
或使用collections.Counter计算可迭代项中唯一项的数量:
from collections import Counter
cnt = Counter('banttnay')
print cnt
像这样的东西:
word = 'banttnay'
res = dict(zip(set(word),map(word.count, word)))