简体   繁体   中英

Swap every Nth element of two lists

I have two lists as:

l1 = [1, 2, 3, 4, 5, 6]
l2 = ['a', 'b', 'c', 'd', 'e', 'f']

I need to swap every N th element of these lists. For example if N=3 , desired result is:

l1 = [1, 2, 'c', 4, 5, 'f']
l2 = ['a', 'b', 3, 'd', 'e', 6]

I can do it via for loop and swap every N th element as:

>>> for i in range(2,len(l1),3):
...     l1[i], l2[i] = l2[i], l1[i]
... 
>>> l1, l2
([1, 2, 'c', 4, 5, 'f'], ['a', 'b', 3, 'd', 'e', 6])

I want to know whether there is much more efficient way to achieve it. May be without for loop.

Note: Length of both lists will be same.

We can achieve that via list slicing as:

>>> l1[2::3], l2[2::3] = l2[2::3], l1[2::3]
>>> l1, l2
([1, 2, 'c', 4, 5, 'f'], ['a', 'b', 3, 'd', 'e', 6])

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