简体   繁体   中英

How to swap even lesser elements with odd greater elements in a python list?

I have a list of elements from 1 to n, ( range(1, n + 1) )

How should I swap odd greater elements with the even elements?

for example, if I have a list with elements [1,2,3] the desired output will be [1,3,2] because odd 3 is greater than even 2 .

example 2:

if list = [1,2,3,4,5]

the desired output will be

[1,3,2,5,4] 

Here 2 will be swapped with 3 and 4 will be swapped with 5 but not with 3 because 3 is smaller than 4.

A simple for loop, to modify the list in place:

l = list(range(1,10))

for i, n in enumerate(l):
    if i % 2 != 0 and i < len(l) - 1:
        l[i] = l[i+1]
        l[i+1] = n

At every odd index, the element swaps places with its successor.

You can use list slicing of even/odd numnbers, zip them and create a solution list from that:

def interleave(n):
    k = list(range(1, n))

    k[:] = k[:1]+[y for x in zip(k[2::2], k[1::2]) 
            for y in x] + (k[-1:] if len(k)%2 == 0 else [])

    return k

print(interleave(20))
print(interleave(21))

Output:

[1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18]
[1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, 17, 16, 19, 18, 20]

Explanation:

  • you keep the 1
  • you get all odd ones from position 2 to end, stepsize 2
  • you get all even ones from position 1 to end, stepsize 2
  • you interleave them using zip
  • you recombine them using a nested list comprehension of [x for y in sequence for y in x] where y are the tuples resulting by zipping two slices
  • you compensate for even/odd sized input lists

Further reading:

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