简体   繁体   中英

Is there a way to change the position of an element of a list iteratively in python?

swepttour = [
    (39.57, 26.15), (36.26, 23.12), (40.56, 25.32), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]

I have such a list and I want to change the position of the second element (element at index 1) iteratively. For example;

Iteration 1:

swepttour = [
    (39.57, 26.15), (40.56, 25.32), (36.26, 23.12), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]

Iteration 2:

swepttour = [
    (39.57, 26.15), (40.56, 25.32), (37.52, 20.44), (36.26, 23.12),    
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]

Is there a way to do it? The first and the last element must be stable.

You can replace slices of a list and that's a common way to transform them. Step through the list and replace 2 element sequences with the same 2 elements swapped. First, start with the data

swepttour = [
    (39.57, 26.15), (36.26, 23.12), (40.56, 25.32), (37.52, 20.44), 
    (38.24, 20.42), (39.36, 19.56), (37.51, 15.17), (35.49, 14.32), 
    (38.15, 15.35), (38.47, 15.13), (38.42, 13.11), (37.56, 12.19), 
    (41.17, 13.05), (33.48, 10.54), (41.23, 9.1), (36.08, -5.21), 
    (39.57, 26.15)
]

Then get rid of it in favor of a sequence that makes the example easier to see in action

swepttour = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']

Then go through the range of indicies and swap 2 element slices

print(swepttour)
for i in range(1, len(swepttour)-2):
    swepttour[i:i+2] = swepttour[i+1], swepttour[i]
    print(swepttour)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM