Home > Software engineering >  Rearrange the tuple by sorting in python
Rearrange the tuple by sorting in python

Time:08-29

I have two lists. One list contains X coordinate values and second list contains Y coordinate values. Using these two lists, I want to make a tupple which is sorted by their first element.

X coordinate = [2, 3, 4, 4, 3, 2, 1, 0, 0, 1, 1, 1, 1, 2, 2, 2]
Y coordinate = [3, 3, 3, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0, 0, 1, 2]

I want my output like this:

[(0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 3), (4, 4)]

To achieve this result, I wrote below code and got an output mentioend below.

merged_list = list(tuple(zip(X3_coordinate, Y3_coordinate)))
merged_list.sort(key=lambda x: x[0])
merged_list

Output:

[(0, 4), (0, 3), (1, 4), (1, 3), (1, 2), (1, 1), (1, 0), (2, 3), (2, 4), (2, 0), (2, 1), (2, 2), (3, 3), (3, 4), (4, 3), (4, 4)]

Kindly let me know what I am doing wrong and give some suggestions of code.

CodePudding user response:

  • instead of list(tuple()) just do list()
  • sort with no key, it'll do element-wise by default
  • use sorted do both generate the list and sort
X_coordinate = [2, 3, 4, 4, 3, 2, 1, 0, 0, 1, 1, 1, 1, 2, 2, 2]
Y_coordinate = [3, 3, 3, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0, 0, 1, 2]
merged_list = sorted(zip(X_coordinate, Y_coordinate))
print(merged_list)

CodePudding user response:

You've sorted by x, but not later by y:

merged_list.sort(key=lambda x: (x[0], x[1]))

[(0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 3), (4, 4)]

CodePudding user response:

By using "key=lambda x: x[0]", you are forcing it to be sorted only by the first element, what you seek is a sort where-in you give priority to the first element, but if the values are same you wish to sort it by the subsequent elements.

X3_coordinate = [2, 3, 4, 4, 3, 2, 1, 0, 0, 1, 1, 1, 1, 2, 2, 2]
Y3_coordinate = [3, 3, 3, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0, 0, 1, 2]
merged_list = list(zip(X3_coordinate, Y3_coordinate))
merged_list.sort()
print(merged_list)

Output:

[(0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 3), (4, 4)]
  • Related