如何在Python列表中切换两个项目的位置? [英] How to switch position of two items in a Python list?
本文介绍了如何在Python列表中切换两个项目的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法在网上找到一个很好的解决此问题的方法(可能是因为switch,position,list和Python都是这样的重载词).
I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words).
这很简单-我有以下列表:
It’s rather simple – I have this list:
['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
我想切换'password2'
和'password1'
的位置-不知道它们的确切位置,只知道它们紧挨着,而password2
在最前面.
I’d like to switch position of 'password2'
and 'password1'
– not knowing their exact position, only that they’re right next to one another and password2
is first.
我已经完成了一些比较漫长的列表下标操作,但是我想知道是否可以提出一些更优雅的方法?
I’ve accomplished this with some rather long-winded list-subscripting, but I wondered its possible to come up with something a bit more elegant?
推荐答案
i = ['title', 'email', 'password2', 'password1', 'first_name',
'last_name', 'next', 'newsletter']
a, b = i.index('password2'), i.index('password1')
i[b], i[a] = i[a], i[b]
这篇关于如何在Python列表中切换两个项目的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文