网站建设导航栏变化,wordpress adminlte,一尊网 又一个wordpress站点,专科网站开发简历统计字符串出现最多的字母及其出现次数
另外如果次数相同按字母顺序排序。
方法1
可以使用自定义键对c.most_common()进行排序#xff0c;该键首先考虑频率的降序#xff0c;然后考虑字母的降序#xff08;请注意lambda x: (-x[1], x[0]) #xff09;#xff1a;
from col…统计字符串出现最多的字母及其出现次数
另外如果次数相同按字母顺序排序。
方法1
可以使用自定义键对c.most_common()进行排序该键首先考虑频率的降序然后考虑字母的降序请注意lambda x: (-x[1], x[0])
from collections import Counter
def ordered_letters(s, n3):
c Counter(s.replace( , ))
top_n sorted(c.most_common(), keylambda x: (-x[1], x[0]))[:n]
for i, t in enumerate(top_n):
c, f t
if i 0: print(1st most frequent, c ., Appearances:, f)
elif i 1: print(2nd most frequent, c ., Appearances:, f)
elif i 2: print(3rd most frequent, c ., Appearances:, f)
else: print(str(i 1) th most frequent, c ., Appearances, f)
sent china construction bank
ordered_letters(sent, 5)
# 1st most frequent n. Appearances: 4
# 2nd most frequent c. Appearances: 3
# 3rd most frequent a. Appearances: 2
# 4th most frequent i. Appearances 2
# 5th most frequent o. Appearances 2
方法2
常规方式对Counter的元组进行排序 但第一个参数-count本身被取反。 这将产生一个反向列表但第二个元组元素将按字母顺序排序。 然后取最后n个项目。
from collections import Counter
ordinal lambda n: %d%s % (n,tsnrhtdd[(n/10%10!1)*(n%104)*n%10::4])
def ordered_letters(s, n3):
ctr Counter(c for c in s if c.isalpha())
ctr sorted(ctr.items(), keylambda x: (-x[1], x[0]))[:n]
for index,value in enumerate(ctr):
print {:s} most frequent: {:}. Appearances: {:}.format(ordinal(index1),value[0],value[1])
s achina aconstruction banck
ordered_letters(s, n3)
结果
1st most frequent: a. Appearances: 4
2nd most frequent: c. Appearances: 4
3rd most frequent: n. Appearances: 4
要想成为python这领域的高手必须了解和弄懂python常见问题。要我们来进行python高手修炼吧。或者你有更好的问题可以留言。