Getting two tuples from a list

I just pulled some data from the list using python, but I find it complicated and untested, and there is probably a much better way to do this. I'm actually very sure that I saw it somewhere in standard library documents, but my brain refuses to tell me where.

So here it is:

Input:

x = range(8) # any even sequence

Conclusion:

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

My welcome:

[ [x[i], x[i+1]] for i in range(len(x))[::2] ]
+3
source share
4 answers

Tuple?

In Python 2.n

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

In Python 3.n

zip() behaves a little 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 in Python 2 and 3 is the same ...

>>> [[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 divide into list3 or more elements without writing it, for example:

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

zip(*2*[iter(x)]) ( , !), zip(*[iter(s)]*n) Python?.

. , , , .

+7

, :

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

Input:

x = range(8) # any even sequence

Decision:

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

Conclusion:

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

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 sure there is no helper function for this.

0
source

All Articles