2013-11-01 312 views
3

我有这样的4个项目的列表:重新排序Python列表

a, b, c, d = [1, 2, 3, 4] 

我重新排序列表,翻转每对:

[b, a, d, c] 

有没有办法在一个做到这一点表达?我试过使用列表理解和解包,但似乎无法做到正确。

我有[1,2,3,4]。我试图得到[2,1,4,3]。

+0

http://stackoverflow.com/a/2493980/1628832? – karthikr

+0

你能详细说明你想要的输入和输出是什么吗? – jterrace

+0

难道你不想要''[2,1,4,3]'作为输出吗? – Christian

回答

8

更一般地,如果你正在寻找翻转对数字的列表:

>>> L = [1, 2, 3, 4, 5, 6] 
>>> from itertools import chain 
>>> list(chain.from_iterable(zip(L[1::2], L[::2]))) 
[2, 1, 4, 3, 6, 5] 
0

你的意思是这样的:

>>> a, b, c, d = [1, 2, 3, 4] 
>>> b, a, d, c = a, b, c, d 
>>> a 
2 
>>> b 
1 
>>> c 
4 
>>> d 
3 

+0

不,我不想重新分配变量,我试图从[1,2,3,4] – nathancahill

5

看看这个:

>>> lst = [1, 2, 3, 4] 
>>> [y for x in zip(*[iter(lst)]*2) for y in x[::-1]] 
[2, 1, 4, 3] 
>>> 
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
>>> [y for x in zip(*[iter(lst)]*2) for y in x[::-1]] 
[2, 1, 4, 3, 6, 5, 8, 7, 10, 9] 
>>> 
+0

得到[2,1,4,3]。将不得不花费一些时间弄清楚这是如何工作的。 – nathancahill

+0

@nathancahill - 谢谢。我假设你理解列表理解部分。我用'zip'和'iter'做的事情是一个非常有用的技巧,你应该记住(它已经用了很多,并且会帮助你)。这里是它的参考:http://stackoverflow.com/questions/18541215/how-do-you-access-a-list-in-group-of-3-in-python向下滚动到@ abarnert的答案。 – iCodez

+0

太棒了,谢谢你的回答和参考。 – nathancahill

2

如果这是只有约4成员列表 - 这将足够了:

list = [1, 2, 3, 4] 
reordered_list = [list[1], list[0], list[3],list[2]] 
+0

嘿家伙 - 为什么downvote完全正确的答案? – Artur

0

试试这个名单悟解决方案:

a = [1,2,3,4,5,6] # Any list with even number of elements 
b = [a[e+1] if (e%2 == 0) else a[e-1] for e in range(len(a))] 

如果列表a具有偶数个元素,这种方法正常。

0
In [1]: l = [1, 2, 3, 4] 

In [2]: list(chain(*map(reversed, zip(l[::2], l[1::2])))) 
Out[2]: [2, 1, 4, 3] 
1

因为绝对没有人给上通用iterables问题的解答,

from itertools import chain 

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 

zip(*[iter(items)]*2) 
#>>> <zip object at 0x7fd673afd050> 

[itms for itms in zip(*[iter(items)]*2)] 
#>>> [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)] 

所以zip(*[iter(x)]*2)意味着ix = iter(x); zip(ix, ix)这对每个元素。

然后你就可以逆转:

[(y, x) for (x, y) in zip(*[iter(items)]*2)] 
#>>> [(2, 1), (4, 3), (6, 5), (8, 7), (10, 9)] 

放到一起,并压平:

[itm for (x, y) in zip(*[iter(items)]*2) for itm in (y, x)] 
#>>> [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] 

这是通用短!


如果你想要的东西在genericism牺牲速度更快,你会很难更好这样的:

new = list(items) 
new[::2], new[1::2] = new[1::2], new[::2] 

new 
#>>> [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] 

请注意,这仍然适用于任意iterables,但也有少层抽象;你不能轻易颠倒翻转的子列表的大小,并且不能输出迭代数等。

+0

优秀的答案。感谢您一步一步的将其分解。 – nathancahill

0

我是否错过了什么?重新订购given_list带回路:

rez = [] 
for i in range(len(given_list)-1, -1, -1): 
    rez.append(given_list[i]) 
return rez