I have zip two lists which I’m trying to sort the tuple by A1 B1 C1
l1 = ['F2', 'G2', 'B2', 'H2', 'A3', 'E3', 'G3', 'C1', 'D1', 'E1', 'D2', 'C3', 'A1']
l2 = [40, 40, 90, 90, 90, 90, 90, 120, 120, 120, 120, 120, 90]
Code
l1, l2 = [list(i) for i in zip(*sorted(zip(l1, l2), key=lambda x: list(map(int,x[0][1:]))))]
print (l1)
print (l2)
Current output:
['C1', 'D1', 'E1', 'A1', 'F2', 'G2', 'B2', 'H2', 'D2', 'A3', 'E3', 'G3', 'C3']
[120, 120, 120, 90, 40, 40, 90, 90, 120, 90, 90, 90, 120]
The expected result should instead be:
l1 = ['A1', 'C1', 'D1', 'E1', 'B2', 'D2', 'F2', 'G2', 'H2', 'A3', 'C3', 'E3', 'G3']
How do I get the expected result instead of what I currently get?
>Solution :
I am not really sure what your code is trying to do. I can get your desired result as follows:
l1 = list(sorted(l1, key=lambda item: (item[1], item[0])))
print(l1)
Output:
['A1', 'C1', 'D1', 'E1', 'B2', 'D2', 'F2', 'G2', 'H2', 'A3', 'C3', 'E3', 'G3']
Note: This solution only works if the items in l1 are two characters in length ('A10' would not be sorted properly).
You don’t show l2 in your desired result.
Update
If you want to sort both lists at the same time, you can combine them as follows:
combined = zip(l1, l2)
combined = list(sorted(combined, key=lambda item: (item[0][1], item[0][0])))
print(combined)
Output:
[('A1', 90), ('C1', 120), ('D1', 120), ('E1', 120), ('B2', 90), ('D2', 120), ('F2', 40), ('G2', 40), ('H2', 90), ('A3', 90), ('C3', 120), ('E3', 90), ('G3', 90)]
To unzip the combined result use these statements:
l1_sorted = [item[0] for item in combined]
l2_sorted = [item[1] for item in combined]
You can also use the zip function for unzipping as explained here.