How to switch position of two items in a Python li

2020-01-23 05:36发布

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']

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?

标签: python list
7条回答
我只想做你的唯一
2楼-- · 2020-01-23 06:03
for i in range(len(arr)):
    if l[-1] > l[i]:
        l[-1], l[i] = l[i], l[-1]
        break

as a result of this if last element is greater than element at position i then they both get swapped .

查看更多
Melony?
3楼-- · 2020-01-23 06:12

I am not an expert in python but you could try: say

i = (1,2)

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

above would give o/p as:

res(1, 2) = (2,1)
查看更多
女痞
4楼-- · 2020-01-23 06:15

Given your specs, I'd use 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']

The right-hand side of the slice assignment is a "reversed slice" and could also be spelled:

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

if you find that more readable, as many would.

查看更多
看我几分像从前
5楼-- · 2020-01-23 06:18

The simple Python swap looks like this:

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

Now all you need to do is figure what i is, and that can easily be done with index:

i = foo.index("password2")
查看更多
等我变得足够好
6楼-- · 2020-01-23 06:19

How can it ever be longer than

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

That's just a plain swap using temporary storage.

查看更多
我命由我不由天
7楼-- · 2020-01-23 06:19

you can use for example:

>>> 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']
查看更多
登录 后发表回答