From: Tycho Andersen on 8 May 2010 17:00 On Sat, May 8, 2010 at 3:41 PM, Oltmans <rolf.oltmans(a)gmail.com> wrote: > Hi, I've a list that looks like following > > a = [ [1,2,3,4], [5,6,7,8] ] > > Currently, I'm iterating through it like > > for i in [k for k in a]: > for a in i: > print a > > but I was wondering if there is a shorter, more elegant way to do it? How about itertools? In python 2.6: >>> a = [ [1,2,3,4], [5,6,7,8] ] >>> from itertools import chain >>> for i in chain(*a): .... print i .... 1 2 3 4 5 6 7 8
From: Oltmans on 8 May 2010 17:06 On May 9, 1:53 am, superpollo <ute...(a)esempio.net> wrote: > add = lambda a,b: a+b > for i in reduce(add,a): > print i This is very neat. Thank you. Sounds like magic to me. Can you please explain how does that work? Many thanks again.
From: Günther Dietrich on 8 May 2010 17:09 Tycho Andersen <tycho(a)tycho.ws> wrote: >On Sat, May 8, 2010 at 3:41 PM, Oltmans <rolf.oltmans(a)gmail.com> wrote: >> Hi, I've a list that looks like following >> >> a = [ [1,2,3,4], [5,6,7,8] ] >> >> Currently, I'm iterating through it like >> >> for i in [k for k in a]: >> for a in i: >> print a >> >> but I was wondering if there is a shorter, more elegant way to do it? > >How about itertools? In python 2.6: > >>>> a = [ [1,2,3,4], [5,6,7,8] ] >>>> from itertools import chain >>>> for i in chain(*a): >... print i >... >1 >2 >3 >4 >5 >6 >7 >8 Why not this way? >>> a = [[1,2,3,4], [5,6,7,8]] >>> for i in a: .... for j in i: .... print(j) .... 1 2 3 4 5 6 7 8 Too simple? Best regards, Günther
From: Tycho Andersen on 8 May 2010 17:40 On Sat, May 8, 2010 at 4:09 PM, Günther Dietrich <gd.usenet(a)spamfence.net> wrote: [snip] > Too simple? No, not at all. I really only intended to point the OP to itertools, because it does lots of useful things exactly like this one. \t
From: Lie Ryan on 9 May 2010 01:17 On 05/09/10 07:09, Günther Dietrich wrote: > > Why not this way? > >>>> a = [[1,2,3,4], [5,6,7,8]] >>>> for i in a: > .... for j in i: > .... print(j) > .... > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > > Too simple? IMHO that's more complex due to the nested loop, though I would personally do it as: a = [ [1,2,3,4], [5,6,7,8] ] from itertools import chain for i in chain.from_iterable(a): print i so it won't choke when 'a' is an infinite stream of iterables.
First
|
Prev
|
Next
|
Last
Pages: 1 2 3 Prev: [ANN] Pyspread 0.1.1 released Next: A more general solution |