說的有點繞口,舉個經(jīng)常調(diào)用的例子:
對如下元組的list排序:students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
使用lambda函數(shù):sorted(students, key=lambda student : student[2])
或者itemgetter:sorted(students, key=operator.itemgetter(2))
很簡潔,一句話。但是是建立在函數(shù)支持這樣指定key的接口。
那假如我想將所有成績求個平均值?提取所有人名打印出去?
有沒有比較簡潔有效的寫法?感覺循環(huán)遍歷訪問總是有點不爽...
2 回答

波斯汪
TA貢獻1811條經(jīng)驗 獲得超4個贊
題主不想寫所謂的循環(huán)大概是指不想寫顯示的for while循環(huán)遍歷吧。
處理一些序列,除了迭代和遞歸,也沒有別的方法了吧。
不想用顯示的for循環(huán),寫成一句話可以使用列表解析,或者使用map,filter,reduces函數(shù)式函數(shù),或者兩者配合使用
python
In [1]: students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] In [2]: map(lambda t: t[0], students) Out[2]: ['john', 'jane', 'dave'] In [3]: reduce(lambda x, y: x + y, map(lambda t: t[-1], students)) / float(len(students)) Out[3]: 12.333333333333334

搖曳的薔薇
TA貢獻1793條經(jīng)驗 獲得超6個贊
試試列表解析式?
例如說提取所有人名
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> names = [ i[0] for i in students ]
>>> names
['john', 'jane', 'dave']
求平均值
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> score = sum([ i[2] for i in students ])
>>> score
37
>>> score/len(students)
12.333333333333334
添加回答
舉報
0/150
提交
取消