Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #108548

Re: More list building

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: More list building
Date 2016-05-12 11:08 +0200
Organization None
Message-ID <mailman.606.1463044097.32212.python-list@python.org> (permalink)
References <ngvph0$osu$1@dont-email.me> <9983c36a-7c06-45b6-9ab8-845eee5915d9@googlegroups.com> <nh1h5o$9ql$1@ger.gmane.org>

Show all headers | View raw


louis.a.russ@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.)

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

More list building DFS <nospam@dfs.com> - 2016-05-11 13:21 -0400
  Re: More list building louis.a.russ@gmail.com - 2016-05-11 19:51 -0700
    Re: More list building Peter Otten <__peter__@web.de> - 2016-05-12 11:08 +0200
      Re: More list building DFS <nospam@dfs.com> - 2016-05-12 12:35 -0400
    Re: More list building DFS <nospam@dfs.com> - 2016-05-12 07:36 -0400
  Re: More list building marco.nawijn@colosso.nl - 2016-05-12 01:21 -0700
    Re: More list building DFS <nospam@dfs.com> - 2016-05-12 08:05 -0400

csiph-web