How to sort a list based of values inside it's elements? SOLVED
Question:
Knowing that the values inside the list num, num2 will change, the idea is to sort the output list, or the lists that form the output, based on the sorted num2.
This is the code:
letter = ['A','B','C','D','E']
num = [7,6,1,1,1]
num2 = [24000,20900,5250,4500,5000]
output = []
for i in range(len(letter)):
output.append((letter[i], num[i], num2[i]))
Current Output:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('D', 1, 4500), ('E', 1, 5000)]
Expected Output:
[(’A’, 7, 24000), (’B’, 6, 20900), (’C’, 1, 5250), (’E’, 1, 5000), (’D’, 1, 4500)]
Answers:
zip
then sort:
output = sorted(zip(letter, num, num2), key=lambda x: x[2], reverse=True)
print(*output)
Output:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('E', 1, 5000), ('D', 1, 4500)]
Using list comprehension you could avoid the temporary assignment altogether as well.
[(x, y, z) for x, y, z in sorted(zip(letter, num, num2), key=lambda thus: thus[2], reverse=True)]
result:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('E', 1, 5000), ('D', 1, 4500)]
Knowing that the values inside the list num, num2 will change, the idea is to sort the output list, or the lists that form the output, based on the sorted num2.
This is the code:
letter = ['A','B','C','D','E']
num = [7,6,1,1,1]
num2 = [24000,20900,5250,4500,5000]
output = []
for i in range(len(letter)):
output.append((letter[i], num[i], num2[i]))
Current Output:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('D', 1, 4500), ('E', 1, 5000)]
Expected Output:
[(’A’, 7, 24000), (’B’, 6, 20900), (’C’, 1, 5250), (’E’, 1, 5000), (’D’, 1, 4500)]
zip
then sort:
output = sorted(zip(letter, num, num2), key=lambda x: x[2], reverse=True)
print(*output)
Output:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('E', 1, 5000), ('D', 1, 4500)]
Using list comprehension you could avoid the temporary assignment altogether as well.
[(x, y, z) for x, y, z in sorted(zip(letter, num, num2), key=lambda thus: thus[2], reverse=True)]
result:
[('A', 7, 24000), ('B', 6, 20900), ('C', 1, 5250), ('E', 1, 5000), ('D', 1, 4500)]