【Python】【排序】字符串列表排序/题目排序/首字母排序
一、首字母排序
说明:有一个字符串列表 然后根据字符串的第一个字母 对这个字符串列表进行排序
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : @Author : @File : @Version : @Function: """ from typing import List class SortStr: @staticmethod def __find_pha(str_olds: List[str]): """ 过滤字符串中的非字母字符 :param str_olds: 原始字符串 如:[--?—He teaches physics i(What is your father)] :return: 过滤后的新字符串 如:[HeteachesphysicsiWhatisyourfather] """ str_news = [] for str_old in str_olds: str_new = '' for char_old in str_old: if char_old.isalpha(): str_new += char_old str_news.append(str_new) return str_news @staticmethod def __sort_str(str_olds: List[str], reverse: bool = False, target_index: int = 0): """ 对字符串列表排序 :param str_olds: 原始字符串列表 :param reverse: False-正序,True-倒序 :param target_index: 需要排序的字符在字符串中的序号(从0开始) :return: """ # 全部转为大写 str_olds_tem = [] for i in str_olds: str_olds_tem.append(i.upper()) # 排序(针对list中的字符串首字母排序) sort_index = [] for i in str_olds_tem: sort_index.append({ 'key': str_olds_tem.index(i), 'value': i[target_index] }) reverse = reverse if reverse else False sort_index = sorted(sort_index, key=lambda e: e.__getitem__('value'), reverse=reverse) # 排序后的序号 ture_index = [] for i in sort_index: ture_index.append(i.get('key')) return ture_index @staticmethod def start(str_old, *args, **kwargs): """ 开始调用 :param str_old: :param args: :param kwargs: reverse=True 倒序 默认正序 :return: """ str1 = SortStr.__find_pha(str_old) ture_index = SortStr.__sort_str(str1, *args, **kwargs) ture_str = [] for i in ture_index: ture_str.append(str_old[i]) return ture_str if __name__ == '__main__': str_o = [ "--?—de teaches physics i(What is your father)", "--?—I’m suffering fr(What's the matter with)", "--?—Well, they got there l(How long have y)", "--?—bes, what size is t(Anything I can do fo)", "--?—Aou too! (Merry Christmas!)", "--?—AAu too! (Merry Christmas!)", ] print('*' * 20 + '排序前' + '*' * 20) print(*str_o, sep='\n') print('\n' + '*' * 20 + '排序后(正序)' + '*' * 20) print(*SortStr.start(str_o), sep='\n') print('\n' + '*' * 20 + '排序后(倒序)' + '*' * 20) print(*SortStr.start(str_o, reverse=True), sep='\n') print('\n' + '*' * 20 + '排序后(对第二个字母字符排序)' + '*' * 20) print(*SortStr.start(str_o, target_index=1), sep='\n')
输出
二、所有字母排序
说明:有一个字符串列表 然后根据字符串的 每一个字母 依次递归对这个字符串列表进行排序
如果忍耐算是坚强 我选择抵抗 如果妥协算是努力 我选择争取
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义