How to sort a list of tuples but with one specific tuple being the first?
I'm doing an application to find the best path for a delivery.
The delivery send me his path:
[
('0', '1'),
('1', '2'),
('0', '2'),
('2', '0')
]
... where every pair of numbers is a location and smallest numbers are closer. They also send me their starting point. For example: 2
.
I did a function to sort from lower to higher:
def lowToHigh(trajet):
trajet_opti = trajet
print(sorted(trajet_opti)开发者_运维问答)
lowToHigh([
('0', '1'),
('1', '2'),
('0', '2'),
('2', '0')
])
The output is like this:
[('0', '1'), ('0', '2'), ('1', '2'), ('2', '0')]
I need a function who puts the tuple with the starting number first:
def starting_tuple():
starting_number = 2
.
.
.
Which returns something like this:
[('2', '0'), ('0', '1'), ('0', '2'), ('1', '2')]
Sort with a key
that adds another tuple element representing whether the list item equals the starting point.
>>> path = [
... ('0', '1'),
... ('1', '2'),
... ('0', '2'),
... ('2', '0')
... ]
>>> sorted(path, key=lambda c: (c[0] != '2', c))
[('2', '0'), ('0', '1'), ('0', '2'), ('1', '2')]
The expression c[0] != '2'
will be False
(0) for the starting point and True
(1) for all others, which will force the starting point to come at the start of the list. If there are multiple starting points, they will be sorted normally relative to each other.
To sort the list of tuples so that the tuple with the starting number is first, you can simply iterate through the list of tuples and check each tuple to see if it contains the starting number. If it does, you can move that tuple to the front of the list. Here's an example of how you could implement this:
def starting_tuple(trajet, starting_number): # Iterate through the list of tuples for i, tup in enumerate(trajet): # Check if the tuple contains the starting number if starting_number in tup: # If it does, move the tuple to the front of the list trajet.insert(0, trajet.pop(i)) break
# Return the sorted list of tuples with the starting tuple first
return trajet
enter code here
Here's an example of how you could use this function:
trajet = [ ('0', '1'), ('1', '2'), ('0', '2'), ('2', '0')]
starting_number = 2
print(starting_tuple(trajet, starting_number))
Output: [('2', '0'), ('0', '1'), ('0', '2'), ('1', '2')]
Note that this function assumes that the starting number is always present in the list of tuples. You may want to add some additional error-checking to handle cases where the starting number is not present in the list.
精彩评论