如何使用冒泡排序在Python 3中对列表进行排序然后再进行子排序 [英] How to do a sort and then a subsort on a list in Python 3 using a bubble sort

查看:63
本文介绍了如何使用冒泡排序在Python 3中对列表进行排序然后再进行子排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我正在参加的课程研究奖金问题.假设我们有一个列表,例如 mylist = [a1,b2,a3,c1,b1,a5,b3,c9] .我想使用基本的Python而不导入任何东西.我想按字母顺序对列表进行排序,然后对每个字母按数字排序.因此,结果将是列表[a1,a3,a5,b1,b2,b3,c1,c9].我正在为数字实现简单的冒泡排序,但是如何对字母进行子排序(或者反之亦然?)

I am working on a bonus question for a course I am taking. Suppose we have a list such as mylist=[a1, b2, a3, c1, b1, a5, b3, c9]. I want to use basic Python without importing anything. I want to sort the list into, first, alphabetical order, and then for each letter, I sort by number. The result would thus be be the list [a1, a3, a5, b1, b2, b3, c1, c9]. I am implementing a simple bubble sort for the numbers, but how do I sub-sort the letters (or, perhaps, vice versa?)

推荐答案

通过两个键使用 sorted list.sort :

my_list = ["a1", "b2", "a3", "c1", "b1", "a5", "b3", "c9"]
sorted(my_list, key=lambda x:(x[0], int(x[1:])))
# ['a1', 'a3', 'a5', 'b1', 'b2', 'b3', 'c1', 'c9']

这篇关于如何使用冒泡排序在Python 3中对列表进行排序然后再进行子排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆