gpt4 book ai didi

python - 如何从python中的列表中排序元组值

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:36 25 4
gpt4 key购买 nike

我有元组值列表。我需要从元组列表中按 id 对值进行排序。谁能帮我做这件事。

  l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]

我需要这样的输出。

  l = [('shankar','10'),('ghi','11'),('sugan','12'),('abc','23')]

而且如果我需要这样排序的话

  l =  [('abc', '23'),('sugan', '12'),('ghi', '11'),('shankar', '10')]

最佳答案

您可以将 key 参数传递给 sorted 函数。

>>> l = [('abc','23'),('ghi','11'),('sugan','12'),('shankar','10')]
>>> sorted(l, key=lambda x: int(x[1]))
[('shankar', '10'), ('ghi', '11'), ('sugan', '12'), ('abc', '23')]
>>>

关于python - 如何从python中的列表中排序元组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33730551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com