说的有点绕口,举个经常调用的例子:
对如下元组的list排序:students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
使用lambda函数:sorted(students, key=lambda student : student[2])
或者itemgetter:sorted(students, key=operator.itemgetter(2))
很简洁,一句话。但是是建立在函数支持这样指定key的接口。
那假如我想将所有成绩求个平均值?提取所有人名打印出去?
有没有比较简洁有效的写法?感觉循环遍历访问总是有点不爽...
The questioner doesn’t want to write the so-called loop, probably because he doesn’t want to write the displayed for while loop traversal.
To deal with some sequences, there is no other way except iteration and recursion.
If you don’t want to use an explicit for loop, you can write it in one sentence using list parsing, or using map, filter, reducers functional functions, or a combination of both
Try list comprehension?
For example, extract the owner’s name
Find the average value