More list building

marco.nawijn at colosso.nl marco.nawijn at colosso.nl
Thu May 12 04:21:29 EDT 2016


On Wednesday, May 11, 2016 at 7:22:09 PM UTC+2, DFS wrote:
> Have:
> p1 = ['Now', 'the', 'for', 'good']
> p2 = ['is', 'time', 'all', 'men']
> 
> want
> [('Now','is','the','time'), ('for','all','good','men')]
> 
> This works:
> 
> p = []
> for i in xrange(0,len(p1),2):
> 	p.insert(i,(p1[i],p2[i],p1[i+1],p2[i+1]))
> 
> 
> But it seems clunky.
> 
> Better way(s)?
> 
> Thanks

Another way using some array manipulation:
(using Python 2.7 and numpy)

# coding: utf-8
import numpy as np

p1 = np.array(('Now', 'the', 'for', 'good'))
p2 = np.array(('is', 'time', 'all', 'men'))

p1s = np.split(p1, 2)
p2s = np.split(p2, 2)

a1 = np.vstack((p1, p2))

r1 = np.hstack((a1[:, 0], a1[:, 1]))
r2 = np.hstack((a1[:, 2], a1[:, 3]))

print r1
print r2

Produces the following output:
['Now' 'is' 'the' 'time']
['for' 'all' 'good' 'men']



More information about the Python-list mailing list