解包与压缩 | *sequence, reduce | reduce快速字典重新整理,参考#3
1 ''' 2 解包与压缩 3 *sequence,reduce 4 reduce快速字典重新整理,参考#3 5 ''' 6 from functools import reduce 7 primes = [1,2,3,4] 8 def product(*numbers): 9 p = reduce(lambda x, y: x*10+y, numbers) 10 print(numbers) 11 print(p) 12 p=product(*primes) ##*解压,reduce()压缩 13 p=product(primes,[1]) 14 15 ''' 16 reduce官方文档定义(部分):'一次处理两个参数' 17 Apply a function of two arguments cumulatively to the items of a sequence, 18 from left to right, so as to reduce the sequence to a single value. 19 ———————————————— 20 21 在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的过程中, 22 reduce工作过程: 23 1、首先把 前两个元素传给 函数参数,函数加工后, 24 2、然后把得到的结果和第三个元素作为两个参数传给函数参数, 25 3、函数加工后得到的结果又和第四个元素作为两个参数传给函数参数,依次类推 26 ''' 27 #1 28 numbers = [1,2,3,4] 29 p = reduce(lambda x, y: x*10+y, numbers,1) 30 print(p)#没1输出1234,有1输出11234 31 32 #2 33 from functools import reduce 34 scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, 35 {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, 36 {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, 37 {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) 38 def reducer(accumulator , value): 39 #print(accumulator , value) 40 sum = accumulator + value['age'] 41 return sum 42 total_age = reduce(reducer, scientists, 0)#0作为reducer初始值,当wequence为空;或作为第一个值 43 print(total_age)#输出467 44 #可用一行下面行数实现 45 sum([x['age'] for x in scientists ])#467 46 47 #3 reduce快速字典重新整理, 48 from functools import reduce 49 scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'}, 50 {'name':'Dennis Ritchie', 'age':76, 'gender':'male'}, 51 {'name':'Ada Lovelace', 'age':202, 'gender':'female'}, 52 {'name':'Frances E. Allen', 'age':84, 'gender':'female'}) 53 def group_by_gender(accumulator , value): 54 accumulator[value['gender']].append(value['name']) 55 return accumulator 56 grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]}) 57 print(grouped)