1

I have a list

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]

It is actually a 1-D representation of a series of 2-D points. The even-indexed values are x values, and the odd ones are y.

I now wish to convert A into

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

What is the most pythonic way of doing so?

Sibbs Gambling
  • 19,274
  • 42
  • 103
  • 174
  • @kojiro Mine is tuple. That one is list. – Sibbs Gambling Oct 11 '13 at 02:43
  • 1
    But not only do several of the solutions given in that question produce tuples, just like yours, pretty much all of them can be trivially converted to produce tuples instead of lists by calling `tuple`. – DSM Oct 11 '13 at 02:47

3 Answers3

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)]
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
6

How about

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

or, as @Igonato suggested in the comments, a neater way to say the same is:

B=[(A[i],A[i+1]) for i in range(0,len(A),2)]
Jakob Weisblat
  • 7,450
  • 9
  • 37
  • 65
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)]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502