列表排序


# 使用sort()列表行原地排序会修改原列表
# 要想列表行排序同又不修改原列表,可以先复制列表

1 unordered_list = [3, 5, 1, 7, 2, 8, 4, 9, 0, 6]
2 print("Output #88: {}".format(unordered_list))
3 list_copy = unordered_list[:]
4 list_copy.sort()
5 print("Output #89: {}".format(list_copy))
6 print("Output #90: {}".format(unordered_list))

个示例展示了使用 sort 函数以 in-place 方式列表行排序的方法。和 reverse
数一种原地排序将原列表修改排好序的新列表。要想使用排好序的列表而
不修改原列表,可以先复制列表,然后列表副本sort 操作。
10. sorted 排序函数
# 使用sorted()一个列表集合按照列表中某个位置的元素行排序

my_lists = [[1,2,3,4], [4,3,2,1], [2,4,1,3]]
my_lists_sorted_by_index_3 = sorted(my_lists, key=lambda index_value:\
index_value[3])
print("Output #91: {}".format(my_lists_sorted_by_index_3))

个示例展示了如何使用 sorted 函数以及关字函数,一个列表集合按照每个列表
中特定索引位置的值进行排序。关字函数置用于列表排序的关字。在个示例中,
字是一个 lambda 函数,表示使用索引位置3 (也就是列表中的第四个元素)
列表行排序。(后将会lambda 函数做更多讨论。)使用每个列表中的第四
个元素作排序关字,sorted 函数之后,第二个列表 [4, 3, 2, 1] 了第
一个列表,第三个列表 [2, 4, 1, 3] 了第二个列表,第一个列表 [1, 2, 3,
4] 了第三个列表。另外,你应该知道 sorted 函数的排序与 sort 函数的 in-place
原地排序方式不同,sort 函数改了原列表的元素序,sorted 函数返回一个新的
排好序的列表,并不改原列表的元素序。
下一个排序示例使用 operator 准模个模提供的功能可以使用多个关
列表、元和字典行排序。了在脚本中使用 operator 中的 itemgetter
数,在脚本上方添加 from operator import itemgetter

1 #!/usr/bin/env python3
2 from math import exp, log, sqrt
3 import re
4 from datetime import date, time, datetime, timedelta
5 from operator import itemgetter

operator 中的 itemgetter 函数后,你可以使用每个列表中多个索引位置
值对列表集合行排序:
# 使用itemgetter()一个列表集合按照两个索引位置来排序

1 my_lists = [[123,2,2,444], [22,6,6,444], [354,4,4,678], [236,5,5,678], [578,1,1,290], [461,1,1,290]]
2 my_lists_sorted_by_index_3_and_0 = sorted(my_lists, key=itemgetter(3,0))
3 print("Output #92: {}".format(my_lists_sorted_by_index_3_and_0))

个示例展示了如何使用 sorted() 函数和 itemgetter 函数按照每个列表中多个索
引位置的值对列表集合行排序。关字函数置用于列表排序的关字。在个示例
中,关字是包含两个索引3 0)的 itemgetter 函数。句的意是:先按
照索引位置 3 中的值对列表行排序,然后,在个排序基上,按照索引位置 0 中的
列表一步排序。
种通多个元素列表和其他数据容器

转载于:https://www.cnblogs.com/baobao-meng/p/8469225.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值