python元组的列表或者列表的列表,如何简单快速计算每个item的指定单元?
大家讲道理
大家讲道理 2017-04-17 15:20:41
0
2
687

说的有点绕口,举个经常调用的例子:
对如下元组的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的接口。
那假如我想将所有成绩求个平均值?提取所有人名打印出去?
有没有比较简洁有效的写法?感觉循环遍历访问总是有点不爽...

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(2)
黄舟

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

pythonIn [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
伊谢尔伦

Try list comprehension?

For example, extract the owner’s name

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> names = [ i[0] for i in students ]
>>> names
['john', 'jane', 'dave']

Find the average value

>>> 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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template