栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

无需复杂的逻辑,只需通过切片和步骤重新排列列表即可:

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]: lOut[3]: [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]

TLDR;

编辑带说明

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

要了解列表切片,这里已经有一个很好的答案和列表切片符号的说明。简单的说:

a[start:end] # items start through end-1a[start:]    # items start through the rest of the arraya[:end]      # items from the beginning through end-1a[:]         # a copy of the whole arrayThere 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 elementsl[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]

希望我不要让大家对这个添加的解释感到困惑。如果是这样,请帮助我的更新并使其更好:-)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号