如何在 Python 列表中切换两个项目的位置? [英] How to switch position of two items in a Python list?
问题描述
我在网上一直没能找到很好的解决这个问题的方法(可能是因为 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屋!