1 | sort([cmp[, key[, reverse]]]) |
1 2 3 4 | >>> l = [43, 12, 4, 6] >>> l.sort() >>> l [4, 6, 12, 43] |
1 2 3 | >>> d = {1: 'z', 2:'y', 3: 'x'} >>> print sorted(d.items(), key=lambda x: x[1]) [(3, 'x'), (2, 'y'), (1, 'z')] |
1 2 3 4 | >>> from collections import OrderedDict >>> sorted_d = OrderedDict(sorted(d.items(), key=lambda x: x[1])) >>> sorted_d OrderedDict([(3, 'x'), (2, 'y'), (1, 'z')]) |
key parameter to specify a function to be called on each list element prior to making comparisons. The value of the key parameter should be a function that takes a single argument and returns a key to use for sorting purposes.
1 2 3 | >>> s = "Sorting1234" >>> "".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x))) 'ginortS1324' |
1 2 3 4 5 6 7 8 9 | def isPalindrome(x): if x < 0: return False reversed_x = 0 original_x = x while x > 0: reversed_x = reversed_x * 10 + x % 10 x /= 10 return reversed_x == original_x |
1 2 | def isPalindrome(x): return x >= 0 and str(x) == str(x)[::-1] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # 函数式编程 >>> nums = map(int, "123456789" ) >>> nums [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 15 >>> sum(nums) 45 # 生成器 >>> mygenerator = (x*x for x in range(3)) >>> for i in mygenerator: ... print i ... 0 1 4 >>> for i in mygenerator: ... print i ... # lambda 匿名函数 >>> c = lambda *z: z >>> c( 10, 'test') (10, 'test') # 迭代 >>> l = [i**2 for i in range(9)] >>> l_iter = iter(l) >>> next(l_iter) 0 >>> next(l_iter) 1 >>> next(l_iter) 4 # 数据结构 set >>> set_a = set([i for i in range(1,9,2)]) >>> set_b = set([i for i in range(0,9,2)]) >>> print set_a | set_b set([0, 1, 2, 3, 4, 5, 6, 7, 8]) |
1 2 3 4 | def reverseBits(n): bit_str = '{0:032b}'.format(n) reverse_str = bit_str[::-1] return int(reverse_str, 2) |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |