1

我有一个清单

A=[9.6, 7.9, 19.4, 13.3, 31.0, 16.1, 44.3, 16.4, 55.7, 16.5, 66.6, 16.7, 77.7, 17.7, 88.7, 19.0, 101.8, 21.0]

它实际上是一系列二维点的一维表示。偶数索引值为 x 值,奇数索引值为 y。

我现在想转换A

B=[(9.6, 7.9), (19.4, 13.3), (31.0, 16.1), (44.3, 16.4), (55.7, 16.5), (66.6, 16.7), (77.7, 17.7), (88.7, 19.0), (101.8, 21.0)]

这样做的最pythonic方式是什么?

4

3 回答 3

7
In [60]: A=[9.6, 7.9, 19.4, 13.3, 31.0, 16.1, 44.3, 16.4, 55.7, 16.5, 66.6, 16.7, 77.7, 17.7, 88.7, 19.0, 101.8, 21.0]

In [61]: zip(A[::2], A[1::2])
Out[61]: 
[(9.6, 7.9),
 (19.4, 13.3),
 (31.0, 16.1),
 (44.3, 16.4),
 (55.7, 16.5),
 (66.6, 16.7),
 (77.7, 17.7),
 (88.7, 19.0),
 (101.8, 21.0)]

In [62]: zip(itertools.islice(A, 0, len(A), 2), itertools.islice(A, 1, len(A), 2))
Out[62]: 
[(9.6, 7.9),
 (19.4, 13.3),
 (31.0, 16.1),
 (44.3, 16.4),
 (55.7, 16.5),
 (66.6, 16.7),
 (77.7, 17.7),
 (88.7, 19.0),
 (101.8, 21.0)]
于 2013-10-11T02:47:32.663 回答
6

怎么样

B=[(A[2*i],A[2*i+1]) for i in range(len(A)/2)]

或者,正如@Igonato 在评论中所建议的那样,一种更简洁的表达方式是:

B=[(A[i],A[i+1]) for i in range(0,len(A),2)]
于 2013-10-11T02:44:24.143 回答
3
>>> A = [9.6, 7.9, 19.4, 13.3, 31.0, 16.1, 44.3, 16.4, 55.7, 16.5, 66.6, 16.7, 77.7, 17.7, 88.7, 19.0, 101.8, 21.0]
>>> zip(*[iter(A)]*2)
[(9.6, 7.9), (19.4, 13.3), (31.0, 16.1), (44.3, 16.4), (55.7, 16.5), (66.6, 16.7), (77.7, 17.7), (88.7, 19.0), (101.8, 21.0)]
于 2013-10-11T02:54:10.087 回答