在列表中交换两个子列表 [英] Swapping two sublists in a list

查看:63
本文介绍了在列表中交换两个子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下列表:

my_list=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

我希望能够尽快高效地将子列表my_list[2:4]与子列表my_list[7:10]交换,以获取新列表:

I want to be able to swap the sub-list my_list[2:4] with the sub-list my_list[7:10] as quickly and as efficiently as possible, to get the new list:

new_list=[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]

这是我的尝试:

def swap(s1, s2, l):

    seg1=l[:s1.start]+l[s2]
    seg2=l[s1.stop : s2.start]
    seg3=l[s1]+l[s2.stop:]

    return seg1+seg2+seg3


print swap(slice(2,4), slice(7,10), [0,1,2,3,4,5,6,7,8,9,10,11,12])

这确实可以打印出所需的输出,尽管这种方式对我来说看起来很糟糕.

This does print the desired output, although this way of doing it looks awful to me.

是否有更简便,更优雅的方法来完成,因此不会为每个函数调用创建四个新列表? (我打算多次调用此函数)

Is there a more easy and elegant way of doing it, that will not create four new lists for every function call? (I plan to call this function a lot)

我不介意(实际上我更愿意)更改原始列表,而不是每个函数调用都创建新实例.

I don't mind (actually I'd prefer) changing the original list, rather than creating new instance every function call.

推荐答案

可以分配切片.

两个变量可以与a, b = b, a交换.

合并以上两个:

>>> my_list[7:10], my_list[2:4] = my_list[2:4], my_list[7:10]
>>> my_list
[0, 1, 7, 8, 9, 4, 5, 6, 2, 3, 10, 11, 12]


请注意-如果切片的大小不同-顺序很重要:如果以相反的顺序交换,最终结果会有所不同,因为它将首先更改初始值项(较低的索引),然后是较高索引的项(但那些项将在第一次分配时移动到不同的位置).


Beware that - if slices have different sizes - the order is important: If you swap in the opposite order, you end up with a different result, because it will change first the initial items (lower indices), and then the higher index items (but those will be shifted in a different position by the first assignment).

此外,切片不得重叠.

这篇关于在列表中交换两个子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆