More list building
Peter Otten
__peter__ at web.de
Thu May 12 05:08:04 EDT 2016
louis.a.russ at gmail.com wrote:
> On Wednesday, May 11, 2016 at 1:22:09 PM UTC-4, 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
>
> Would this work for you? Or do you need something more general?
> t = list(zip(p1,p2))
> p = [t[0]+t[1],t[2]+t[3]]
This can be generalized as
>>> t = iter(zip(p1, p2))
>>> [a + b for a, b in zip(t, t)]
[('Now', 'is', 'the', 'time'), ('for', 'all', 'good', 'men')]
(The iter() call can be omitted in Python 3.)
More information about the Python-list
mailing list