Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 交换两个列表中的每n个元素_Python_List_Swap - Fatal编程技术网

Python 交换两个列表中的每n个元素

Python 交换两个列表中的每n个元素,python,list,swap,Python,List,Swap,我有两份清单: l1 = [1, 2, 3, 4, 5, 6] l2 = ['a', 'b', 'c', 'd', 'e', 'f'] 我需要交换这些列表中的每个Nth元素。例如,如果N=3,所需结果为: l1 = [1, 2, 'c', 4, 5, 'f'] l2 = ['a', 'b', 3, 'd', 'e', 6] 我可以通过for循环完成,并将每个Nth元素交换为: >>> for i in range(2,len(l1),3): ... l1[i], l

我有两份清单:

l1 = [1, 2, 3, 4, 5, 6]
l2 = ['a', 'b', 'c', 'd', 'e', 'f']
我需要交换这些列表中的每个
N
th元素。例如,如果
N=3
,所需结果为:

l1 = [1, 2, 'c', 4, 5, 'f']
l2 = ['a', 'b', 3, 'd', 'e', 6]
我可以通过
for
循环完成,并将每个
N
th元素交换为:

>>> 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])
我想知道是否有更有效的方法来实现这一目标。对于循环,可能没有


注意:两个列表的长度将相同。

我们可以通过
列表切片实现这一点,如下所示:

>>> 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])

我刚想到要通过网络来做这件事<代码>列表切片
,我认为这非常有效。我仍然很想知道是否有更好的方法。不要删除问题,因为它可能对其他人有帮助。