Python_Tips[3] -> sort/sorted 排序函数

排序函数 / Sort Function


 

list自带的sort函数可以实现对列表的排列功能,具有同样功能的还有sorted函数。

基本形式

列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可修改的。sort函数是基于原有的列表进行修改,因此若是需要备份原始列表则可以通过列表的切片实现(若是直接赋值则被赋值列表会跟随原始列表变化)。

1 # List built-in function, sort
2 x = [4, 2, 5, 3, 8, 3]
3 
4 # Slice up the list x, then generate a new list y
5 y = x[:]
6 x.sort()
7 print(x) # [2, 3, 3, 4, 5, 8]
8 print(y) # [4, 2, 5, 3, 8, 3]

而sorted函数与sort的功能类似,但sorted不仅可以操作列表,还可以操作字符串与字典等,操作字典时返回的是字典键值的排序列表。

1 y = sorted(y) # [2, 3, 3, 4, 5, 8]
2 
3 z = sorted('python') # ['h', 'n', 'o', 'p', 't', 'y']
4 z = sorted({3: 'c', 4: 'w', 1: 'c'}) # [1, 3, 4]

可选参数

sort和sorted函数可选的参数主要有两个,key和reevrse,其中key提供一个在排序过程中每次都会调用的函数,reverse则确定排序的大小顺序。

1 # key parameter
2 x = ['mmm', 'm', 'mmmm', 'mmmmm', 'mm'] 
3 x.sort(key=len) # ['m', 'mm', 'mmm', 'mmmm', 'mmmmm']
4 sorted(x, key=len) # ['m', 'mm', 'mmm', 'mmmm', 'mmmmm']
5 
6 # reverse parameter
7 x = ['3', '2', '1', '6', '4'] 
8 x.sort(key=int, reverse=True) # ['6', '4', '3', '2', '1']
9 sorted(x, key=int, reverse=False) # ['1', '2', '3', '4', '6']

 

参考链接


http://www.jb51.net/article/52730.htm

转载于:https://www.cnblogs.com/stacklike/p/8227605.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct node { int data; struct node *next; } node; void insert(node **head, int value) { node *new_node = (node *)malloc(sizeof(node)); new_node->data = value; new_node->next = *head; *head = new_node; } void print(node *head) { while (head) { printf("%d ", head->data); head = head->next; } } void insertion_sort(node **head) { if (*head == NULL || (*head)->next == NULL) { return; } node *sorted_list = NULL; // 已排序部分的链表头指针 node *cur = *head; // 待排序部分的当前节点 while (cur != NULL) { node *prev_sorted = NULL; // 已排序部分的前一个节点 node *cur_sorted = sorted_list; // 已排序部分的当前节点 // 在已排序部分中找到待插入位置 while (cur_sorted != NULL && cur_sorted->data > cur->data) { prev_sorted = cur_sorted; cur_sorted = cur_sorted->next; } // 将待排序节点插入到已排序链表中 if (prev_sorted == NULL) { // 待插入位置在链表头 node *temp = cur->next; // 先保存下一个节点,以便后面遍历链表时继续访问 cur->next = sorted_list; sorted_list = cur; cur = temp; } else { // 待插入位置在链表中间或尾部 prev_sorted->next = cur; node *temp = cur->next; // 先保存下一个节点,以便后面遍历链表时继续访问 cur->next = cur_sorted; cur = temp; } } *head = sorted_list; // 更新头指针 } int main() { node *head = NULL; srand((unsigned int)time(0)); for (int i = 0; i < 10; ++i) { int a = rand() %100; insert(&head,a); } printf("原始链表:"); print(head); insertion_sort(&head); printf("\n排序后的链表:"); print(head); getchar(); return 0; }如何换成冒泡排序进行排序
06-09

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值