简体   繁体   中英

How to sort my list by descending numbers and ascending alphabet?

I want to sort a list of lists

l = [[2, 'Horror'], [2, 'Romance'], [2, 'Comedy'], [3, 'Action'], [1, 'Adventure'], [2, 'History']]

and want this output that sort first by numbers in descending order and then by alphabet in ascending order:

[[3, 'Action'], [2, 'Comedy'], [2, 'History'], [2, 'Horror'], [2, 'Romance'], [1, 'Adventure']]

but I receive this using sorted(l, reverse=True) :

[[3, 'Action'], [2, 'Romance'], [2, 'Horror'], [2, 'History'], [2, 'Comedy'], [1, 'Adventure']]

We can sort using a lambda function:

lst = [[2, 'Horror'], [2, 'Romance'], [2, 'Comedy'], [3, 'Action'], [1, 'Adventure'], [2, 'History']]
output = sorted(lst, key=lambda x: (-x[0], x[1]))
print(output)

# [[3, 'Action'], [2, 'Comedy'], [2, 'History'], [2, 'Horror'], [2, 'Romance'], [1, 'Adventure']]

you can sort like this,

test_list = ["1", "G", "7", "L", "9", "M", "4"]

print("The original list is: " + str(test_list))

numerics = []

alphabets = []

for sub in test_list:

if sub.isnumeric():

    numerics.append(sub)
else:
    alphabets.append(sub)

res = sorted(alphabets) + sorted(numerics)

print("The Custom sorted result: " + str(res))

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