Python字符串统计以及排序

我们的目的是统计字符串中字幕出现的次数,而字典提供了我们一个很好的方法,来统计字幕的出现次数:

>>> letterCounts = {}
>>> for letter in "Mississippi"
SyntaxError: invalid syntax
>>> letterCounts
{}
>>> for letter in "Fjdhsjdfhsjdkfds":
	letterCounts[letter] = letterCounts.get(letter,0)+1

	
>>> letterCounts
{'f': 2, 's': 3, 'd': 4, 'F': 1, 'h': 2, 'k': 1, 'j': 3}
>>> 

Python中有两个items和sort能够更好的完成这一个功能:

>>> letterCounts.items()
dict_items([('f', 2), ('s', 3), ('d', 4), ('F', 1), ('h', 2), ('k', 1), ('j', 3)])
>>> sorted(letterCounts.items())
[('F', 1), ('d', 4), ('f', 2), ('h', 2), ('j', 3), ('k', 1), ('s', 3)]

对于排序,我看了写书上写的,但是部分代码运行不了,一查才知道一些函数的使用范围在Python3.2,3.3之后的使用对象不太一样了,做了一些调整

这篇博客写的挺不错的:http://tech.ddvip.com/2013-02/1361016871190339.html


>>> b = ['aa' , 'asds' , 'EWE' , 'DDDFFRR']
>>> b
['aa', 'asds', 'EWE', 'DDDFFRR']
>>> sorted(b)
['DDDFFRR', 'EWE', 'aa', 'asds']
>>> sorted(b,key = len)
['aa', 'EWE', 'asds', 'DDDFFRR']
>>> sorted(b,key = str.lower)
['aa', 'asds', 'DDDFFRR', 'EWE']
>>> def lastLetter(s):
	return s[-1]

>>> sorted(b,key=lastLetter)
['EWE', 'DDDFFRR', 'aa', 'asds']

你可能感兴趣的:(python,sort,sorted,字典)