user150340
user150340

Reputation:

Getting two-tuples out of a list

I just extracted some data from a list using python but think it's overcomplicated and unpythonic and there's probably a much better way to do this. I'm actually pretty sure I saw this somewhere in the standard library docs but my brain refuses to tell me where.

So here it goes:

Input:

x = range(8) # any even sequence

Output:

[[0, 1], [2, 3], [4, 5], [6, 7]]

My take:

[ [x[i], x[i+1]] for i in range(len(x))[::2] ]

Upvotes: 3

Views: 3837

Answers (4)

johnsyweb
johnsyweb

Reputation: 141780

Tuples?

In Python 2.n

>>> zip(*2*[iter(x)])
[(0, 1), (2, 3), (4, 5), (6, 7)]

In Python 3.n

zip() behaves slightly differently...

>> zip(*2*[iter(x)])
<zip object at 0x285c582c>
>>> list(zip(*2*[iter(x)])])
[(0, 1), (2, 3), (4, 5), (6, 7)]

Lists?

The implementation is the same in Python 2 and 3...

>>> [[i,j] for i,j in zip(*2*[iter(x)])]
[[0, 1], [2, 3], [4, 5], [6, 7]]

Or, alternatively:

>>> [list(t) for t in zip(*2*[iter(x)])]
[[0, 1], [2, 3], [4, 5], [6, 7]]

The latter is more useful if you want to split into lists of 3 or more elements, without spelling it out, such as:

>>> [list(t) for t in zip(*4*[iter(x)])]
[[0, 1, 2, 3], [4, 5, 6, 7]]

If zip(*2*[iter(x)]) looks a little odd to you (and it did to me the first time I saw it!), take a look at How does zip(*[iter(s)]*n) work in Python?.

See also this pairwise implementation, which I think is pretty neat.

Upvotes: 6

gsbabil
gsbabil

Reputation: 7703

Input:

x = range(8) # any even sequence

Solution:

output = []
for i, j in zip(*[iter(x)]*2):
    output.append( [i, j] )

Output:

print output
[[0, 1], [2, 3], [4, 5], [6, 7]]

Upvotes: 1

Mariy
Mariy

Reputation: 5914

If you want tuples instead of lists you can try:

>>> zip(range(0, 8, 2), range(1, 8, 2))
[(0, 1), (2, 3), (4, 5), (6, 7)]

Upvotes: 1

AndiDog
AndiDog

Reputation: 70128

You can rewrite it a bit:

>>> l = range(8)
>>> [[l[i], l[i+1]] for i in xrange(0, len(l), 2)]
[[0, 1], [2, 3], [4, 5], [6, 7]]

For some list tasks you can use itertools, but I'm pretty sure there's no helper function for this one.

Upvotes: 0

Related Questions