Move an item inside a list?

前端 未结 6 530
-上瘾入骨i
-上瘾入骨i 2020-11-29 01:58

In Python, how do I move an item to a definite index in a list?

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 02:45

    If you don't know the position of the item, you may need to find the index first:

    old_index = list1.index(item)
    

    then move it:

    list1.insert(new_index, list1.pop(old_index))
    

    or IMHO a cleaner way:

    try:
      list1.remove(item)
      list1.insert(new_index, item)
    except ValueError:
      pass
    

提交回复
热议问题