我一直沒有找到一個很好的解決方案在網絡上的這個問題(可能是因爲開關,位置,列表和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