¿Cómo cambiar la posición de dos elementos en una lista de Python?


No he podido encontrar una buena solución para este problema en la red (probablemente porque switch, position, list y Python son palabras sobrecargadas).

Es bastante simple-tengo esta lista:

['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']

Me gustaría cambiar la posición de 'password2' y 'password1' – sin saber su posición exacta, solo que están justo al lado uno del otro y password2 es el primero.

He logrado esto con algunas listas bastante largas, pero me preguntaba si era posible venir con algo un poco más elegante?

Author: mikl, 2010-03-22

8 answers

    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]
 290
Author: samtregar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 16:31:49

El intercambio simple de Python se ve así:

foo[i], foo[j] = foo[j], foo[i]

Ahora todo lo que necesitas hacer es calcular lo que es i, y eso se puede hacer fácilmente con index:

i = foo.index("password2")
 122
Author: Can Berk Güder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 16:30:05

Dadas sus especificaciones, usaría slice-assignment:

>>> L = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
>>> i = L.index('password2')
>>> L[i:i+2] = L[i+1:i-1:-1]
>>> L
['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']

El lado derecho de la asignación de slice es un "slice invertido"y también podría escribirse:

L[i:i+2] = reversed(L[i:i+2])

Si usted encuentra que más legible, como muchos lo harían.

 15
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 16:35:28

¿Cómo puede ser más largo que

tmp = my_list[indexOfPwd2]
my_list[indexOfPwd2] = my_list[indexOfPwd2 + 1]
my_list[indexOfPwd2 + 1] = tmp

Eso es solo un intercambio simple usando almacenamiento temporal.

 5
Author: unwind,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 16:27:40

Puedes usar por ejemplo:

>>> test_list = ['title', 'email', 'password2', 'password1', 'first_name',
                 'last_name', 'next', 'newsletter']
>>> reorder_func = lambda x: x.insert(x.index('password2'),  x.pop(x.index('password2')+1))
>>> reorder_func(test_list)
>>> test_list
... ['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']
 0
Author: SmartElectron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-20 07:58:10
for i in range(len(arr)):
    if l[-1] > l[i]:
        l[-1], l[i] = l[i], l[-1]
        break

Como resultado de esto, si el último elemento es mayor que el elemento en la posición i, ambos se intercambian .

 0
Author: ravi tanwar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-15 03:42:50

No soy un experto en python pero podrías intentarlo: say

i = (1,2)

res = lambda i: (i[1],i[0])
print 'res(1, 2) = {0}'.format(res(1, 2)) 

Anterior daría o / p como:

res(1, 2) = (2,1)
 -1
Author: lambzee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-06 12:09:15

Wow! Hay una manera mucho más estándar (aplicable a todos los idiomas), simple y más corta!

x = i[2]; i[2] = i[3]; i[3] = x

Simple es Mejor Que Complejo

Nota: Si no conoce la posición:

index = list.index("password1")  # = 3 in the given list
 -2
Author: Apostolos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-13 22:09:40