python 对中文名字序列排序_python-使用键功能对序列进行排序

It is unclear to me how the following works:

In [1]: student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

In [2]: sorted(student_tuples, key=lambda student: student[2])

Out [2]: [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] # sort by age

but,

In [3]: st = lambda student: student[2]

In [4]: st(student_tuples)

Out [4]: ('dave', 'B', 10)

Why does the [2] in the former sample refer to the index for the individual tuples, when in a lambda function it returns the 2nd tuple in the list?

解决方案

Because when you're sorting, the key function is called once for every element of the list being sorted. That's why it's lambda student: not lambda student_tuples: (not that the naming of parameters changes anything, just explaining the naming choice).

You can see this directly by printing the argument of the key function:

student_tuples = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

def my_key(student):

print(student)

return student[2]

sorted(student_tuples, key=my_key)

# calls to my_key print:

# ('john', 'A', 15)

# ('jane', 'B', 12)

# ('dave', 'B', 10)

my_key(student_tuples)

# prints (not returns):

# [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值