Python在列表中移动多个元素

时间:2019-03-18 17:56:49

标签: python python-3.x list slice

如果从某个索引开始有空格,我需要在列表中移动元素,在移动元素右边的元素一定不能从其索引处移动,这是一个演示:

# desired output
["not end","x","y","","","","don't move"]


# works here
l = ["not end","","","","x","y","don't move"]
start = 1
aext_len = 3
end = start + aext_len + 1

for empty, cell in enumerate(l[start:end - 1], 1):
    if cell:
        break

for z in range(aext_len + 2 - empty):
    l.insert(start + z, l.pop(start + empty + z))
print (l)
#['not end', 'x', 'y', '', '', '', "don't move"]


# not here
l = ["not end","","x","y","","","don't move"]
start = 1
aext_len = 3
end = start + aext_len + 1

for empty, cell in enumerate(l[start:end - 1], 1):
    if cell:
        break

for z in range(aext_len + 2 - empty):
    l.insert(start + z, l.pop(start + empty + z))
print (l)
#['not end', 'y', '', '', '', 'x', "don't move"]

1 个答案:

答案 0 :(得分:2)

解决方案实际上要简单得多。

l = ["not end", "", "", "", "x", "y", "don't move"]

定义“请勿移动”区域的结尾:

MOVE = 6

“挤出”空字符串:

part1 = [x for x in l[:MOVE] if x]

将“挤出的”空字符串移到末尾:

part2 = (MOVE - len(part1)) * [""]

合并片段:

part1 + part2 + l[MOVE:]
#['not end', 'x', 'y', '', '', '', "don't move"]

或者,您可以通过为空字符串的属性对列表的第一部分进行排序:

sorted(l[:MOVE], key=lambda x: x=="") + l[MOVE:]
#['not end', 'x', 'y', '', '', '', "don't move"]