不需要复杂的逻辑,只需使用切片和步长重新排列列表:
In [1]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [2]: l[::2], l[1::2] = l[1::2], l[::2]
In [3]: l
Out[3]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]
TLDR;
编辑并解释
我相信大多数的读者已经熟悉了列表切片和多重赋值。但是如果你还没有,我会尽力解释(希望我不会让它更糟)。
要理解列表切片,这里已经有了一个非常好的回答和列表切片符号的解释。简而言之:
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
让我们来看一下原帖发布者的要求:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # list l
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
0 1 2 3 4 5 6 7 8 9 # respective index of the elements
l[0] l[2] l[4] l[6] l[8] # first tier : start=0, step=2
l[1] l[3] l[5] l[7] l[9] # second tier: start=1, step=2
-----------------------------------------------------------------------
l[1] l[3] l[5] l[7] l[9]
l[0] l[2] l[4] l[6] l[8] # desired output
第一层将是:l[::2] = [1, 3, 5, 7, 9]
第二层将是:l[1::2] = [2, 4, 6, 8, 10]
由于我们想要重新分配first = second
和second = first
,我们可以使用多个赋值,并直接在原始列表中更新:
first , second = second , first
就是说:
l[::2], l[1::2] = l[1::2], l[::2]
顺便提一下,如果想要得到一个新的列表但不改变原来的l
,我们可以从l
中赋值一个新的列表,然后执行上述操作,即:
如果要得到新列表,可以用 list(l)
复制一份新列表进行操作。
n = l[:] # assign n as a copy of l (without [:], n still points to l)
n[::2], n[1::2] = n[1::2], n[::2]
希望我的补充解释没有让你们感到困惑。如果有的话,请帮忙更新并改进它 :-)