Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of tuples in consecutive order

I want to sort a list of tuples in a consecutive order, so the first element of each tuple is equal to the last element of the previous one.

For example:

input = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
output = [(10, 7), (7, 13), (13, 4), (4, 9), (9, 10)]

I have developed a search like this:

output=[]
given = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
t = given[0][0]
for i in range(len(given)):
      # search tuples starting with element t
      output += [e for e in given if e[0] == t]
      t = output[-1][-1] # Get the next element to search

print(output)    

Is there a pythonic way to achieve such order? And a way to do it "in-place" (with only a list)?

In my problem, the input can be reordered in a circular way using all the tuples, so it is not important the first element chosen.

like image 645
Rockcat Avatar asked Dec 19 '16 11:12

Rockcat


People also ask

How to sort the list of tuples in a list?

When it is required to sort the list of tuples in a specific order, the 'sorted' method can be used. The 'sorted' method is used to sort the elements of a list.

How to sort a list based on the last value?

The sorted method in the python library is used to return a sorted list. We will pass parameters to use the last value of tuple to sort the list based on the last value of the tuple. The sort () method also sorts the given list and takes a lambda function for defining the key and order of sorting.

What is tuples in Python?

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable. List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered set of values enclosed in square brackets []. A list of tuples is a list whose each element is a tuple.

How do you call a function from a list of tuple?

A list of tuple is defined, and is displayed on the console. The function is called by passing this list of tuple as parameter. This operation's data is stored in a variable.


1 Answers

Assuming your tuples in the list will be circular, you may use dict to achieve it within complexity of O(n) as:

input = [(10, 7), (4, 9), (13, 4), (7, 13), (9, 10)]
input_dict = dict(input)  # Convert list of `tuples` to dict

elem = input[0][0]  # start point in the new list

new_list = []  # List of tuples for holding the values in required order

for _ in range(len(input)):
    new_list.append((elem, input_dict[elem]))
    elem = input_dict[elem]
    if elem not in input_dict:
        # Raise exception in case list of tuples is not circular
        raise Exception('key {} not found in dict'.format(elem))

Final value hold by new_list will be:

>>> new_list
[(10, 7), (7, 13), (13, 4), (4, 9), (9, 10)]
like image 103
Moinuddin Quadri Avatar answered Oct 14 '22 10:10

Moinuddin Quadri