问题
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?)
回答1:
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']
回答2:
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']
来源:https://stackoverflow.com/questions/54917199/how-to-do-a-sort-and-then-a-subsort-on-a-list-in-python-3-using-a-bubble-sort