简体   繁体   中英

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.

The function accepts two arguments:

old_index - current index of item new_index - index where we want the item to be moved

Let's say I have this list:

list = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

I decide to move letter 'f' before letter 'b'. This means old_index = 5 and 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)) ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM