Python在列表中移动多个元素

问题描述 投票:0回答:1

如果从某个索引开始有空格,我需要移动列表中的元素,移位元素右边的元素不能从它们的索引移动,演示:

# 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"]
python python-3.x list slice
1个回答
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"]
© www.soinside.com 2019 - 2024. All rights reserved.