1. 将数列 a, b, c 对应的值相加
>>> a = range(0, 10) >>> b = range(10,20) >>> c = range(20,30) #有时候像filter/map/reduce这样的"老资格"配合lambda用起来还是挺舒服滴 >>> map(lambda x,y,z: x+y+z, a,b,c) [30, 33, 36, 39, 42, 45, 48, 51, 54, 57] #此处用List Comprehensions 就没那么方便啦 >>> [a[i]+b[i]+c[i] for i in range(len(a))] [30, 33, 36, 39, 42, 45, 48, 51, 54, 57]
2. 将数表中值相加取和(ps. Python 本身就内置了这样的 sum 函数):
>>> mysum = lambda l: reduce(lambda x,y: x+y, l) >>> mysum(range(100) 4950
3. 矩阵变换
>>> mat = [ ... [1, 2, 3], ... [4, 5, 6], ... [7, 8, 9], ... ] # List Comprehensions 最直接 >>> [[row[i] for row in mat] for i in [0, 1, 2]] [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # Functional 也还行 >>> map(lambda i: map(lambda row: row[i], mat), [0, 1, 2]) [[1, 4, 7], [2, 5, 8], [3, 6, 9]] # 也可以用内置的zip函数,不过返回的是list of tuple(这种构造便于作迭代) >>> zip(*mat) [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
#例1用外部迭代器比较好,像Ruby这种采用内部迭代器的语言表达起来不方便 #要么就学习LP采用“原始”的方法: out = [] a.each_with_index { |x, i| out << x+b[i]+c[i] } #例2Ruby可以用open class和inject来完成 class Array def sum inject(nil) { |s, x| s ? s+x : x } end end >>> (1..99).to_a.sum 4950 #例3,Ruby却能完全胜任 >>> (0..2).map { |i| mat.map { |row| row[i] } } [[1, 4, 7], [2, 5, 8], [3, 6, 9]]