1
input_list = ["G1","G2","G5","G4","G3","R1","R2","R3","R5","R4"] 

output_list = ["R1","R2","R3","R4","R5""G1","G2","G3","G5","G4"]

Code I tried:

new_list = []
for i in sorted(input_list):
    new_list.append(i)
print (new_list[::-1])

Actual Output : ['R5', 'R4', 'R3', 'R2', 'R1', 'G5', 'G4', 'G3', 'G2', 'G1']

Expected Output : ["R1", "R2", "R3", "R4", "R5", "G1", "G2", "G3", "G5", "G4"]

0

4 Answers 4

2

It appears that you want to sort descending by the letter component followed by ascending by the number component. One option uses list sort() with a lambda expression:

input_list = ["G1","G2","G5","G4","G3","R1","R2","R3","R5","R4"]
input_list.sort(key=lambda x: (re.sub(r'\d+$', '', x), -int(re.sub(r'^[A-Z]+', '', x))), reverse=True)
print(input_list)

This prints:

['R1', 'R2', 'R3', 'R4', 'R5', 'G1', 'G2', 'G3', 'G4', 'G5']
Sign up to request clarification or add additional context in comments.

2 Comments

Stuff like this really makes me realize that much to learn I still have
@CamiloMartínez I wanted a shorter way of doing this, but this is the best I could come up with.
1

I'm as much of a fan of regular expressions as the next guy, but assuming the elements of the input list are uniform (a single capital letter followed by a single digit), I believe something (arguably) simpler is possible.

unsorted_list = ["G1","G2","G5","G4","G3","R1","R2","R3","R5","R4"]

sorted_list = sorted(unsorted_list, key=lambda x: (-ord(x[0]), x[1]))

print(sorted_list)

Output:

['R1', 'R2', 'R3', 'R4', 'R5', 'G1', 'G2', 'G3', 'G4', 'G5']

Comments

0

unsorted_list = ["G1","G2","G5","G4","G3","R1","R2","R3","R5","R4"]

sorted_list = sorted(unsorted_list, key=lambda x: (-ord(x[0]), x[1]))

print(sorted_list)

Comments

0

inp = ["R1","G2","R5","G1","R4","R2","R3","G4","G3","G5"] #exp_opt = [R1,R2,R3,R4,R5,G1,G2,G3,G4,G5]

print(sorted(inp))

this is the simplest way to sort things apart from using regex

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.