I have a list of tuples where each tuple represents the movement from city x to city y, in this case [(x,y)]. Imagining that I will travel through city a, b, c and d in this order the list would look like this: [(a, b), (b , c), (c, d)] where the first position of the tuple represents the departure and the second the arrival.
I have to swap cities from the final route. Imagining that in the previous example, instead of being a, b, c and d it would be a, d, c and b and the final tuple would be [(a, d), (d , c), (c, b)]. Do you know any way to make this exchange ? It's just that I can't swap the whole tuples, because I'm swapping cities and not the trip. And I have to keep the arrivals and departures coherent.
Thanks.
First of all, tuples are immutable, meaning you cannot change a tuple once it has been created. So you'll need to transform data first, order it the way you like, and then convert it back to tuples.
I suggest you use lists with single element to save route e.g. ['a', 'b', 'c', 'd']
. Swapping element in the list has O(1) complexity, and then you can iterate trough list and create a list of tuples again, something like
l = ['a', 'b', 'c', 'd']
res = []
for i in range(len(l) - 1):
res.append((l[i], l[i+1]))