我需要移动列表中的单个或多个连续项,所谓连续,我的意思是,如果这些项不止一个,那么它们的列表索引中就没有间隙,下面是我尝试过的
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]
由于您没有提到任何有关验证的内容,例如原始列表中是否不存在给定的元素序列、主列表和给定列表的顺序等。我没有考虑任何验证
在开始编写代码之前,让我们看看如何破解解决方案。 首先,您需要确定给定列表在主列表中的现有位置
现在,检查给定列表是向前还是向后移动
解决方案代码:
相关问题 更多 >
编程相关推荐