I'm writing some small apps to learn the language, and I like it a lot
so far.
My problem I've stumbled upon is that I don't know how to do what I
want. I want to do a loop in a loop. I think.
I've got two arrays with some random stuff in, like this.
array1 = ['one','two','three','four']
array2 = ['a','b','c','d']
I want to loop through array1 and add elements from array2 at the end,
so it looks like this:
one a
two b
three c
four c
I'm stuck. I know how to loop through the arrays separatly and print
them, but both at the same time? Hmmm.
A push in the right direction, anyone?
R,
SH
for i in zip(array1, array2):
print i
Although I take it you meant four d, the issue with this method is
that once you hit the end of one array the rest of the other one is
ignored.
Yes, small typo there.
Okey, so if my array1 is has 4 elements, and array2 has 6, it won't
loop trough the last 2 in array2? How do I make it do that?
R,
SH
You could always pre-pad the lists you are using before using the zip
function, kinda like
def pad(*iterables):
max_length = 0
for each_iterable in iterables:
if len(each_iterable) > max_length: max_length =
len(each_iterable)
for each_iterable in iterables:
each_iterable.extend([None for i in xrange(0,max_length-
len(each_iterable))])
pad(array1, array2, array3)
for i in zip(array1, array2, array3):
print i
What you could also do is create an index to use for it.
for i in xrange(0, length_of_longest_list):
try: print array1[i]
except IndexError: pass
try: print array2[i]
except IndexError: pass
couldn't you just do something like
if len(array1) is not len(array2):
if len(array1) < len(array2):
max_length = len(array2) - len(array1)
array1.extend([None for i in xrange(0, max_length)])
elif len(array1) > len(array2):
max_length = len(array1) - len(array2)
array2.extend([None for i in xrange(0, max_length)])
for i in zip(array1, array2):
print i
Though my case only really works for these two, whereas yours can be
used on more than two lists. :)
<ot>
Please gentlemen: Python has no builtin type named 'array', so
s/array/list/g
</ot>
Just pad your shortest list.
I agree, but was merely showing how he would use the variables he had
given.
> You could always pre-pad the lists you are using before using the zip
> function, kinda like
>
> def pad(*iterables):
> max_length = 0
> for each_iterable in iterables:
> if len(each_iterable) > max_length: max_length =
> len(each_iterable)
> for each_iterable in iterables:
> each_iterable.extend([None for i in xrange(0,max_length-
> len(each_iterable))])
>
> pad(array1, array2, array3)
> for i in zip(array1, array2, array3):
> print i
>
Another option is to pad each iterator as it is exhausted. That way you
can use any iterators not just lists. e.g.
from itertools import cycle, chain
def paddedzip(*args, **kw):
padding = kw.get('padding', '')
def generate_padding():
padders = []
def padder():
if len(padders) < len(args)-1:
padders.append(None)
while 1:
yield padding
while 1:
yield padder()
return zip(*(chain(it, pad)
for (it, pad) in zip(args, generate_padding())))
for i in paddedzip(xrange(10), ['one', 'two', 'three', 'four'],
['a', 'b', 'c'], padding='*'):
print i
*never* use the identity operator to test equality ! The fact that
CPython memoize small integers is an implementation detail, *not* a part
of the language specification.
> if len(array1) < len(array2):
> max_length = len(array2) - len(array1)
> array1.extend([None for i in xrange(0, max_length)])
> elif len(array1) > len(array2):
> max_length = len(array1) - len(array2)
> array2.extend([None for i in xrange(0, max_length)])
Never heard of the builtin max() function ?-)
def pad(*lists, **kw):
padding = kw.get('padding', None)
lists_lens = [len(alist) for alist in lists]
padlen = max(lists_lens)
return [
alist + ([padding] * (padlen - list_len))
for list_len, alist in zip(lists_lens, lists)
]
for i in zip(*pad(range(3), range(5, 10))):
print i
Now there are very certainly smart solutions using itertools, but the
one I cooked is way too ugly so I'll leave this to itertools masters !-)
> A push in the right direction, anyone?
for number,letter in zip(array1,array2):
print "%s %s" % (number,letter)
> Okey, so if my array1 is has 4 elements, and array2 has 6, it won't
> loop trough the last 2 in array2? How do I make it do that?
In that case your problem is the data. You'll either have to truncate
one array and/or pad the other.
Or is this what you want?
n = len(array1) if len(array1) < len(array2) else len(array2)
for number,letter in zip(array1[:n],array2[:n]):
print "%s %s" % (number,letter)
reminder = array1[n:] if len(array1) > len(array2) else array2[n:]
for x in reminder: print x
Here's my effort:
from itertools import izip, islice, chain, repeat
def padzip(*xs, **kw):
pad = kw.get('padding', None)
maxlen = max(len(x) for x in xs)
return islice(izip(*[chain(x, repeat(pad)) for x in xs]), maxlen)
--
Paul Hankin
One solution is with map() instead if zip(). map() with None as the
first argument works much like zip(), but it keeps looping if one of the
lists is exhausted. When that happens, it uses None for those values:
words = ['zero', 'one', 'two', 'three']
numbers = [0, 1, 2, 3, 4, 5, 6]
for word, number in map(None, words, numbers):
print word, number
zero 0
one 1
two 2
three 3
None 4
None 5
None 6
--
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
-- Isaac Asimov
Roel Schroeven
The "functional" style is to use the zip function that someone
described. The old-fashioned way is simply:
n = len(array1)
for i in xrange(n):
print array1[i], array2[i]
You can modify this in various ways if the lengths of the lists are
not equal. E.g.
And if the iterables don't necessarily support len(), here's a more
general solution:
from itertools import repeat
def izippad(*iterables, **kw):
pad = kw.get('padding', None)
next_pad = repeat(pad).next
getnext = [iter(iterable).next for iterable in iterables]
pending = size = len(iterables)
while True:
slice = [None] * size
for i in xrange(size):
try: slice[i] = getnext[i]()
except StopIteration:
pending -= 1
if not pending: return
getnext[i] = next_pad
slice[i] = pad
yield slice
George
Instead of counting the exceptions, we can limit the padding iterables
by using an iterator that returns len(iterables) - 1 padding
generators, use a sort of lazy chain, and then just izip.
from itertools import izip, repeat
def chain_next(xs, yg):
for x in xs: yield x
for y in yg.next(): yield y
def izippad(*xs, **kw):
padder = repeat(kw.get('padding', None))
padder_gen = repeat(padder, len(xs) - 1)
return izip(*[chain_next(x, padder_gen) for x in xs])
--
Paul Hankin
Not trying to pick on you personally but there's this disease
when a newbie comes with a basically simple question (in this case,
how to solve the problem with ordinary lists) and gets back a lot
of complex, overly general "graduate level" solutions.
There's a humorous set of Haskell examples that takes this to extremes:
> Not trying to pick on you personally but there's this disease when a
> newbie comes with a basically simple question (in this case, how to
> solve the problem with ordinary lists) and gets back a lot of
> complex, overly general "graduate level" solutions.
Is that a disease?
I would characterise it as symptomatic of a very healthy programming
community. We like interesting problems, and enjoy coming up with ever
more elegant solutions. The discussions that ensue are healthy, not
diseased.
Whether that's exactly what the original poster in such a thread wants
is beside the point. This forum is for the benefit of all
participants, and discussing an apparently simple problem to discover
its complexities is part of the enjoyment.
Enjoyment of the discussion, after all, is the main reward most people
can ever hope to get for participation in most threads here.
--
\ "Remember: every member of your 'target audience' also owns a |
`\ broadcasting station. These 'targets' can shoot back." -- |
_o__) Michael Rathbun to advertisers, news.admin.net-abuse.email |
Ben Finney
> George Sakkis <george.sak...@gmail.com> writes:
> > And if the iterables don't necessarily support len(), here's a more
> > general solution:
>
> Not trying to pick on you personally but there's this disease
> when a newbie comes with a basically simple question (in this case,
> how to solve the problem with ordinary lists) and gets back a lot
> of complex, overly general "graduate level" solutions.
Fair enough, although I don't think it's bad to show more general/
efficient/flexible solutions after the simple quick & dirty ones have
been shown, as in this thread. My solution is just a step further from
Paul Hankin's, not a direct response to the OP.
> There's a humorous set of Haskell examples that takes this to extremes:
>
> http://www.willamette.edu/~fruehr/haskell/evolution.html
Hehe.. I remember seeing a similar one for Java and "Hello world"
using more and more elaborate abstractions and design patterns but I
can't find the link.
George
Well then, in that case, what the heck.
from itertools import *
def padzip(*xs, **kw):
pad = kw.get('padding', None)
ts = izip(*[chain(((y,) for y in x), repeat(None)) for x in xs])
def m(t): return tuple((x[0] if x else pad) for x in t)
return imap(m, takewhile(any, ts))
> Instead of counting the exceptions, we can limit the padding iterables
> by using an iterator that returns len(iterables) - 1 padding
> generators, use a sort of lazy chain, and then just izip.
>
> from itertools import izip, repeat
>
> def chain_next(xs, yg):
> for x in xs: yield x
> for y in yg.next(): yield y
>
> def izippad(*xs, **kw):
> padder = repeat(kw.get('padding', None))
> padder_gen = repeat(padder, len(xs) - 1)
> return izip(*[chain_next(x, padder_gen) for x in xs])
I have had the need for such a 'padded zip' before and my
implementation was eerily similar:
from itertools import repeat, chain, izip
def repeatnext(iterator):
val = iterator.next()
while True: yield val
def longzip(default, *iterables):
defaultgen = repeat(default, len(iterables) - 1)
return izip(*[chain(it, repeatnext(defaultgen)) for it in
iterables])
--
Arnaud
Yek ! Should have read the doc more carefully. Height years of Python,
and I didn't knew this one :(
As far as I'm concerned, it's certainly a GoodThing(tm) - everyone
learns in the process.
This is not linked to Java but deals with Hello World
http://www.ariel.com.au/jokes/The_Evolution_of_a_Programmer.html
Thank you Paul, and everybody else contributing with answers of
various complexity. Although a whole bunch of them was way too complex
for my simple problem, but that's ok.
I now know how to use map and zip, and also learned some tips and
tricks.
Thanks.
All the best,
SH