简体   繁体   中英

How to do a sort and then a subsort on a list in Python 3 using a bubble sort

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?)

Use sorted or list.sort with two keys:

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']

Try this:

mylist=["a20", "b2", "a1", "c1", "b1", "a10", "b3", "c9"]
sorted_list=[]
def fun(l):
    minn = l[0]
    for i in l:
        if i[0]<minn[0]:
            minn = i
        elif i[0] == minn[0]:
            if int(i[1:])<int(minn[1:]):
                minn = i
    l.remove(minn)
    return minn

for i in range(len(mylist)):
    sorted_list.append(fun(mylist))
print(sorted_list)

The result:

['a1', 'a10', 'a20', 'b1', 'b2', 'b3', 'c1', 'c9']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM