Hello, My problem is to order a list (in my case 4 items) [A,B,C,D] all items are tuples i.e.(value1, value2)
we are looking for the element with the smallest value1.
This element has to become the first element in the ordered list, the rest of the list has to be one of the folowing :
[A, B, C, D] or[B, A, D, C] or[C, D, A, B]or[D, C, B, A]
So when C[0] had the smallest value1 the returned list should be in the order [C, D, A, B] independent of the values of the other elements.
I can get this result but the code looks very un-Pythonlike, and I have the feeling that this could be written in a clean way.
we are looking for the element with the smallest value1.
This element has to become the first element in the ordered list, the rest of the list has to be one of the folowing :
[A, B, C, D] or[B, A, D, C] or[C, D, A, B]or[D, C, B, A]
So when C[0] had the smallest value1 the returned list should be in the order [C, D, A, B] independent of the values of the other elements.
I can get this result but the code looks very un-Pythonlike, and I have the feeling that this could be written in a clean way.
Code:
import random random.seed() poly = [] #the points are generated for purpose of explaining what I want to do # in my actual program they are the cornerpoints of a polygone for point in range(4): poly.append((random.randint(0,100), random.randint(0,100))) # gives for instance - -> [(36, 90), (91, 44), (47, 49), (33, 80)] print(poly) #So now I have 4 points in a list [A,B,C,D], I want to rearange them. # if for instance B[1] (= poly[1][1]) = 44 is the smallest from #the 'X'[1] values then the points need to be arranged like [B, A, D, C] # here is my solution, not so pretty... polyAD = (poly[0], poly[3]) polyBC = (poly[1], poly[2]) polyCB = (poly[2], poly[1]) polyDA = (poly[3], poly[0]) polyAB = sorted((polyAD,polyBC), key = lambda pos: pos[0][1]) polyCD = sorted((polyCB,polyDA), key = lambda pos: pos[0][1]) polyABCD = sorted((polyAB,polyCD),key = lambda pos: pos[0][0][1])[0] # now we have to put the second tuple at the back poly =[polyABCD[0][0],polyABCD[1][0],polyABCD[1][1],polyABCD[0][1]] # poly is now ordered as [ABCD],[BADC],[CDAB] or [DCBA] print(poly)
Comment