search

Home  >  Q&A  >  body text

python元组的列表或者列表的列表,如何简单快速计算每个item的指定单元?

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

大家讲道理大家讲道理2860 days ago725

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 15:22:41

    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
    

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:22:41

    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
    

    reply
    0
  • Cancelreply