我们的目的是统计字符串中字幕出现的次数,而字典提供了我们一个很好的方法,来统计字幕的出现次数:
>>> 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} >>>
>>> 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)]
这篇博客写的挺不错的: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']