[英]Create a function that rearranges item in list and shifts the other items (Python)
I'm trying to write a function in Python that would re-arrange specified item, moved it to new position and the other items would shift in relation. 我正在尝试用Python编写一个函数,该函数将重新排列指定的项目,将其移至新位置,其他项目的关系也会发生变化。
The function accepts two arguments: 该函数接受两个参数:
old_index - current index of item new_index - index where we want the item to be moved old_index-项目的当前索引new_index-我们希望将项目移动到的索引
Let's say I have this list: 假设我有以下列表:
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
I decide to move letter 'f' before letter 'b'. 我决定将字母“ f”移动到字母“ b”之前。 This means old_index = 5
and new_index = 1
. 这意味着old_index = 5
和new_index = 1
。 After this operation is done, I want the letters to be shifted, not swapped, resulting in this: 完成此操作后,我希望字母移动而不是交换,结果是:
list = ['a', 'f', 'b', 'c', 'd', 'e', 'g']
I've come up with following function: 我想出了以下功能:
def shift_letters(old_index, new_index):
shifted = list.index(list[old_index])
selected = list[old_index]
print 'selected', selected
list.insert(new_index, selected)
print 'inserted %s at %s' % (selected, new_index)
if old_index < new_index:
removed = list.pop(shifted - 1)
else:
removed = list.pop(shifted + 1)
print 'removed %s' % removed
But that doesn't work very well. 但这不是很好。 I'd like to avoid making copies of the list if possible (lists in my application could be very large). 如果可能,我想避免制作列表的副本(我的应用程序中的列表可能很大)。
Pop from the old index, insert at the desired index. 从旧索引弹出,在所需索引处插入。
>>> mylist = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> old_index = 5
>>> new_index = 1
>>>
>>> mylist.insert(new_index, mylist.pop(old_index))
>>> mylist
['a', 'f', 'b', 'c', 'd', 'e', 'g']
def shift_letters(list, old_index, new_index):
value = list.pop(old_index)
list.insert(new_index, value)
So maybe: 所以也许:
ls.insert(new, ls.pop(old))
? ls.insert(new, ls.pop(old))
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.