473,804 Members | 3,108 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loop in a loop?

Hi,
I'm new to Python and have come across a problem I don't know how to
solve, enter com.lang.python :)

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','th ree','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
Jan 17 '08
23 1736
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
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 !-)
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
Jan 17 '08 #11
Sacred Heart schreef:
On Jan 17, 1:35 pm, cokofree...@gma il.com wrote:
>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?
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
Jan 17 '08 #12
Sacred Heart <sc*****@gmail. comwrites:
array1 = ['one','two','th ree','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
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.
Jan 17 '08 #13
On Jan 17, 12:25 pm, Paul Hankin <paul.han...@gm ail.comwrote:
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.

42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
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 !-)

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
And if the iterables don't necessarily support len(), here's a more
general solution:

from itertools import repeat

def izippad(*iterab les, **kw):
pad = kw.get('padding ', None)
next_pad = repeat(pad).nex t
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
Jan 17 '08 #14
On Jan 17, 7:02*pm, George Sakkis <george.sak...@ gmail.comwrote:
On Jan 17, 12:25 pm, Paul Hankin <paul.han...@gm ail.comwrote:
On Jan 17, 4:38 pm, Bruno Desthuilliers <bruno.
42.desthuilli.. .@wtf.websitebu ro.oops.comwrot e:
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 !-)
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

And if the iterables don't necessarily support len(), here's a more
general solution:

from itertools import repeat

def izippad(*iterab les, **kw):
* * pad = kw.get('padding ', None)
* * next_pad = repeat(pad).nex t
* * 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
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

Jan 18 '08 #15
George Sakkis <ge***********@ gmail.comwrites :
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.

There's a humorous set of Haskell examples that takes this to extremes:

http://www.willamette.edu/~fruehr/ha...evolution.html
Jan 18 '08 #16
Paul Rubin <http://ph****@NOSPAM.i nvalidwrites:
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
Jan 18 '08 #17
On Jan 17, 7:13 pm, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
George Sakkis <george.sak...@ gmail.comwrites :
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/ha...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
Jan 18 '08 #18
Ben Finney <bi************ ****@benfinney. id.auwrites:
Enjoyment of the discussion, after all, is the main reward most people
can ever hope to get for participation in most threads here.
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))
Jan 18 '08 #19
On Jan 17, 11:59*pm, Paul Hankin <paul.han...@gm ail.comwrote:
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(iter ator):
val = iterator.next()
while True: yield val

def longzip(default , *iterables):
defaultgen = repeat(default, len(iterables) - 1)
return izip(*[chain(it, repeatnext(defa ultgen)) for it in
iterables])

--
Arnaud

Jan 18 '08 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2944
by: Charles Alexander | last post by:
Hello I am new to php & MySQL - I am trying to retrieve some records from a MySQL table and redisplay them. The data in list form looks like this: Sample_ID Marker_ID Variation G23_NA17192.fsa rs7374540 A/C I23_Control.fsa rs7374540 C/C
3
5266
by: Anand Pillai | last post by:
This is for folks who are familiar with asynchronous event handling in Python using the asyncore module. If you have ever used the asyncore module, you will realize that it's event loop does not have a programmable exit condition. It keeps looping till the channels in its socket map (a dictionary) are closed and don't have any pending reads/writes. If you are using Python threads in your application, by using either the threading or...
43
5607
by: Gremlin | last post by:
If you are not familiar with the halting problem, I will not go into it in detail but it states that it is impossible to write a program that can tell if a loop is infinite or not. This is a fallacy built on the assumption of mythical infinite all powerfull machines. In reality we deal with finite machines that are capable of two states in a loop, they either terminate, or repeat themselves. In the mythical halting problem scenario...
5
7303
by: Martin Schou | last post by:
Please ignore the extreme simplicity of the task :-) I'm new to C, which explains why I'm doing an exercise like this. In the following tripple nested loop: int digit1 = 1; int digit2 = 0; int digit3 = 0; for( ; digit1 < 5 ; digit1++ ) {
32
4663
by: Toby Newman | last post by:
At the page: http://www.strath.ac.uk/IT/Docs/Ccourse/subsection3_8_3.html#SECTION0008300000000000000 or http://tinyurl.com/4ptzs the author warns: "The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers."
2
2689
by: Alex | last post by:
Compiler - Borland C++ 5.6.4 for Win32 Copyright (c) 1993, 2002 Borland Linker - Turbo Incremental Link 5.65 Copyright (c) 1997-2002 Borland Platform - Win32 (XP) Quite by accident I stumbled across some wierd loop behavior. With the pasted code I receive the output that follows. I realize that the code is broken, because the inner loop fails to reset j for each iteration of the outer loop (the fix is commented out). I also know that...
3
3532
by: Ben R. | last post by:
In an article I was reading (http://www.ftponline.com/vsm/2005_06/magazine/columns/desktopdeveloper/), I read the following: "The ending condition of a VB.NET for loop is evaluated only once, while the C# for loop ending condition is evaluated on every iteration." Is this accurate? I don't understand how you could get away without evaluating the ending condition at every iteration. Otherwise, how would you
32
2612
by: cj | last post by:
When I'm inside a do while loop sometimes it's necessary to jump out of the loop using exit do. I'm also used to being able to jump back and begin the loop again. Not sure which language my memories are of but I think I just said loop somewhere inside the loop and it immediately jumped back to the start of the loop and began again. I can't seem to do that in .net. I this functionality available?
16
3547
by: Claudio Grondi | last post by:
Sometimes it is known in advance, that the time spent in a loop will be in order of minutes or even hours, so it makes sense to optimize each element in the loop to make it run faster. One of instructions which can sure be optimized away is the check for the break condition, at least within the time where it is known that the loop will not reach it. Any idea how to write such a loop? e.g.
2
19318
ADezii
by: ADezii | last post by:
If you are executing a code segment for a fixed number of iterations, always use a For...Next Loop instead of a Do...Loop, since it is significantly faster. Each pass through a Do...Loop that iterates a specified number of times, requires you to also implement or decrement some sort of Loop Counter, while a For...Next Loop does that work for you. Both Loops will provide the same results, but the For...Next Loop is substantially faster. One...
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10308
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10073
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9134
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7609
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6846
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5513
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3806
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2981
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.