python列表元素交换_交换列表中元素的更好方法?

不需要复杂的逻辑,只需通过切片和步骤重新排列列表: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

用解释编辑

我相信大多数观众已经熟悉了列表切片和多重赋值。如果你不这样做,我会尽力解释发生了什么(希望我不要让事情变得更糟)。

为了理解列表切片,here已经对列表切片表示法给出了一个很好的答案和解释。

简单地说: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

让我们看看OP的要求:[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分配一个新列表,并执行上面的操作,即: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]

希望我不会把你们中的任何人和这个附加的解释混淆。如果是,请帮助更新我的并使其更好:-)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值