将列表中的单个或多个连续项移动到任意位置

2024-09-30 01:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要移动列表中的单个或多个连续项,所谓连续,我的意思是,如果这些项不止一个,那么它们的列表索引中就没有间隙,下面是我尝试过的

def move(x, tomove, idx):
    move_start = tomove[0]
    move_end = tomove[-1] + 1
    if idx == len(x) or idx == len(x) - 1:
        return x[:move_start] + x[move_end:] + x[move_start:move_end]
    elif idx == 0:
        return x[move_start:move_end] + x[:move_start] + x[move_end:]
    else:
        pass

# move to start
print (move([0,1,2,3,4,5,6],
            [2],
            0))
# expected output [2,0,1,3,4,5,6]

# move to end
print (move([0,1,2,3,4,5,6],
            [2],
            6))
# expected output [0,1,3,4,5,6,2]

# move forward single
print (move([0,1,2,3,4,5,6],
            [2],
            3))
# expected output [0,1,3,2,4,5,6]

# move backward single
print (move([0,1,2,3,4,5,6],
            [2],
            1))
# expected output [0,2,1,3,4,5,6]

# move forward multiple
print (move([0,1,2,3,4,5,6],
            [2,3],
            5))
# expected output [0,1,4,5,2,3,6]

# move backward multiple
print (move([0,1,2,3,4,5,6],
            [4,5],
            2))
# expected output [0,1,4,5,2,3,6]

Tags: to列表outputmovelenreturnstartend
1条回答
网友
1楼 · 发布于 2024-09-30 01:34:17

由于您没有提到任何有关验证的内容,例如原始列表中是否不存在给定的元素序列、主列表和给定列表的顺序等。我没有考虑任何验证

在开始编写代码之前,让我们看看如何破解解决方案。 首先,您需要确定给定列表在主列表中的现有位置

move_list_pos = lis.index(move_list[0])

现在,检查给定列表是向前还是向后移动

  • 如果它需要向后移动,那么主列表中不会有任何更改 直到新位置,插入给定列表,继续主列表,除了给定列表
  • 如果它需要向前推进,那么主列表应该在那里 除了主列表中的给定列表,直到新位置,添加 给定列表,将主列表从一个新位置继续到最后

解决方案代码:

def move(lis,move_list,pos):
    move_list_pos = lis.index(move_list[0])
    if pos<move_list_pos:
        return lis[:pos]+move_list+lis[pos:move_list_pos]+lis[move_list_pos+len(move_list):]
    else:
        return lis[:move_list_pos]+lis[move_list_pos+len(move_list):pos+1]+move_list+lis[pos+1:]

相关问题 更多 >

    热门问题