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']]
CodePudding user response:
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']]
CodePudding user response:
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))