我一直没有找到一个很好的解决方案在网络上的这个问题(可能是因为开关,位置,列表和Python都是这样重载的话)。如何在Python列表中切换两个项目的位置?
这是相当简单 - 我有这样的名单:
['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
我想切换的'password2'
和'password1'
位置 - 不知道他们的确切位置,只知道他们是对彼此相邻并password2
是第一个。
我已经完成了一些相当冗长的列表下标,但我想知道它有可能想出一些更优雅的东西?
你的问题是试图在列表中找到'password2'的效率吗? 'password1'可以在'password2'之前吗?在你的原始问题中没有遇到复杂性吗? 否则我同意@unwind。 – 2010-03-22 16:31:27
你应该发布你所拥有的 - 我很好奇你的意思是“相当冗长的列表下标”。 – samtregar 2010-03-22 16:33:45
沿着index1 = index('password1')的行; index2 = index('password2'); order = order [:index2] .append(order [index1])。append(order [index2])。append(order [index1 + 1:]);在更多的线上传播。漂亮,没有。 – mikl 2010-03-22 19:06:33