I know how to swap two variables together but I want to know if there is a quicker way to follow a certain pattern.
So I have this list of number. list=[1,2,3,4,5,6]
And what I want to do is to swap a number with the following one and swap the next number with the number after it. so after swapping them it would become list=[2,1,4,3,6,3]
So I was wondering if there was a way to be able to swap the numbers more simply. Thank you.
lst = [1,2,3,4,5,6] # As an example
for x in range(0, len(lst), 2):
if x+1 == len(lst): # A fix for lists which have an odd-length
break
lst[x], lst[x+1] = lst[x+1], lst[x]
This doesn't create a new list.
Edit: Tested and it's even faster than a list comprehension.
If your list has even length, this might be the simplest way:
>>> lst = [1,2,3,4,5,6]
>>> [lst[i^1] for i in range(len(lst))]
[2, 1, 4, 3, 6, 5]
from itertools import chain
from itertools import izip_longest
In [115]: li
Out[115]: [1, 2, 3, 4, 5, 6, 7]
In [116]: [i for i in list(chain(*(izip_longest(li[1::2],li[0::2])))) if i!=None]
Out[116]: [2, 1, 4, 3, 6, 5, 7]
or alternatively if you have even length list
a[start:end:step] # start through not past end, by step
Check this Understanding List slice notation
In [65]: li
Out[65]: [1, 2, 3, 4, 5, 6]
In [66]: new=[None]*(len(li))
In [71]: new[0::2]=li[1::2]
In [73]: new[1::2]=li[0::2]
In [74]: new
Out[74]: [2, 1, 4, 3, 6, 5]
My solution uses funcy
Example:
>>> from funcy import chunks, mapcat
>>> xs = [1, 2, 3, 4, 5, 6]
>>> ys = mapcat(reversed, chunks(2, xs))
>>> ys
[2, 1, 4, 3, 6, 5]
This kinds of reads nicely too; concatenate and map the results of reversing each 2-pair chunks of xs
.
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.