473,770 Members | 4,355 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Enumerate question: Inner looping like in Perl

Hi,

I have Perl code looping thru lines in the file:

line: while (<INFILE>) {
...
$_ = do something
...
if (/#START/) {
# Start inner loop
while (<INFILE>) {
if (/#END/) {
next line;
}
}
}
if (/#BLAH1/) {
$_ = do something
}
if (/#BLAH2/) {
$_ = do something
}
}
I decided to use enumerate() in my Python version
since current line must be modified (the $_ = idiom in Perl)

---code starts---

fh = codecs.open(f_p ath, "rU", "utf-8")
contents = fh.readlines()
fh.close()

# Precompile regular expressions (speed hack?)
findSTART = r'#START'
matcherSTART = re.compile(find START, re.UNICODE)
findEND = r'#END'
matcherEND = re.compile(find END, re.UNICODE)
for i, row in enumerate(conte nts):
row[i] = something
if matcherSTART.se arch(row):
"Oops! how to advance 'i' and 'row' untill:
if matcherEND.sear ch(row):
continue

---code ends---

I could create extra parameter to store the state of the loop like:

foundSTART = False
for i, row in enumerate(conte nts):
if foundSTART:
if not matcherEND.sear ch(row):
continue
else:
foundSTART = False
else:
if matcherSTART.se arch(row):
foundSTART = True
if foundBLAH1:
row[i] = something
if foundBLAH2:
row[i] = something

but is this it really more maintainable code?

Is there enumerate() hack that I am missing or
should I go back to idiom?:

for i in range(len(conte nts)):
if matcherSTART.se arch(row[i]):
while not matcherEND.sear ch(row[i]):
i = i + 1
continue
-pekka-
Jul 18 '05 #1
5 1675
Pekka Niiranen <pe************ @wlanmail.com> wrote:
...
for i, row in enumerate(conte nts):
row[i] = something
if matcherSTART.se arch(row):
"Oops! how to advance 'i' and 'row' untill:
if matcherEND.sear ch(row):
continue
You take an explicit iterator and call its .next() method (or
equivalently use an inner for on the iterator, if that is sufficient, as
it appears to be in this case -- see later).
Is there enumerate() hack that I am missing or
should I go back to idiom?:

for i in range(len(conte nts)):
if matcherSTART.se arch(row[i]):
while not matcherEND.sear ch(row[i]):
i = i + 1
continue


this 'idiom' won't do what you want; i is set again to the very next
value, ignoring all modifications in the loop's body, when execution
gets back to the loop's header.

Here, probably, is what you want:

looper = iter(enumerate( contents))
for i, row in looper:
row[i] = something
if matcherSTART.se arch(row):
for i, row in looper:
if matcherEND.sear ch(row):
break
Alex
Jul 18 '05 #2
Pekka Niiranen <pekka.niiran en <at> wlanmail.com> writes:
for i, row in enumerate(conte nts):
row[i] = something
if matcherSTART.se arch(row):
"Oops! how to advance 'i' and 'row' untill:
if matcherEND.sear ch(row):
continue


Usually I would do this kind of thing by just keeping the iterator around. The
example below has two loops, an outer and an inner, and both iterate over the
same enumeration. (I've used 'char ==' instead of regular expressions to make
the output a little clearer, but hopefully you can do the translation back to
regexps for your code.)
contents = list('abcdefg')
itr = enumerate(conte nts)
for i, char in itr: .... print 'outer', i, char
.... contents[i] = char.upper()
.... if char == 'd':
.... for i, char in itr:
.... print 'inner', i, char
.... if char == 'f':
.... break
....
outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 f
outer 6 g contents

['A', 'B', 'C', 'D', 'e', 'f', 'G']

Steve

Jul 18 '05 #3
Steven Bethard wrote:
Pekka Niiranen <pekka.niiran en <at> wlanmail.com> writes:

for i, row in enumerate(conte nts):
row[i] = something
if matcherSTART.se arch(row):
"Oops! how to advance 'i' and 'row' untill:
if matcherEND.sear ch(row):
continue

Usually I would do this kind of thing by just keeping the iterator around. The
example below has two loops, an outer and an inner, and both iterate over the
same enumeration. (I've used 'char ==' instead of regular expressions to make
the output a little clearer, but hopefully you can do the translation back to
regexps for your code.)

contents = list('abcdefg')
itr = enumerate(conte nts)
for i, char in itr:
... print 'outer', i, char
... contents[i] = char.upper()
... if char == 'd':
... for i, char in itr:
... print 'inner', i, char
... if char == 'f':
... break
...

Thanks, I decided to catch logical error of not
finding "f" -letter at all with:
def myiter(contents ): .... itr = enumerate(conte nts)
.... for i, char in itr:
.... print 'outer', i, char
.... if char == 'd':
.... try:
.... for i, char in itr:
.... print 'inner', i, char
.... if char == 'f':
.... break
.... except StopIteration:
.... print "f not found"
.... contents = list('abcdeg')
myiter(contents )
outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 g

Not working: Iter() takes care of its own exceptions?
This recurring feeling that writing REALLY correct programs in Python
is not easier than in lower level languages... :(

-pekka-


outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 f
outer 6 g
contents


['A', 'B', 'C', 'D', 'e', 'f', 'G']

Steve

Jul 18 '05 #4
On Sun, 31 Oct 2004 12:28:47 +0200, Pekka Niiranen <pe************ @wlanmail.com> wrote:
Steven Bethard wrote:
Pekka Niiranen <pekka.niiran en <at> wlanmail.com> writes:

for i, row in enumerate(conte nts):
row[i] = something
if matcherSTART.se arch(row):
"Oops! how to advance 'i' and 'row' untill:
if matcherEND.sear ch(row):
continue

Usually I would do this kind of thing by just keeping the iterator around. The
example below has two loops, an outer and an inner, and both iterate over the
same enumeration. (I've used 'char ==' instead of regular expressions to make
the output a little clearer, but hopefully you can do the translation back to
regexps for your code.)

>contents = list('abcdefg')
>itr = enumerate(conte nts)
>for i, char in itr:


... print 'outer', i, char
... contents[i] = char.upper()
... if char == 'd':
... for i, char in itr:
... print 'inner', i, char
... if char == 'f':
... break
...

Thanks, I decided to catch logical error of not
finding "f" -letter at all with:
def myiter(contents ):... itr = enumerate(conte nts)
... for i, char in itr:
... print 'outer', i, char
... if char == 'd':

#XXX# >... #try:... for i, char in itr:
... print 'inner', i, char
... if char == 'f':
... break else:
print "f not found"
#XXX >... #except StopIteration:
#XXX >... # print "f not found"... contents = list('abcdeg')
myiter(contents )outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 g

Not working: Iter() takes care of its own exceptions?
This recurring feeling that writing REALLY correct programs in Python
is not easier than in lower level languages... :(

-pekka-


outer 0 a
outer 1 b
outer 2 c
outer 3 d
inner 4 e
inner 5 f
outer 6 g
>contents


['A', 'B', 'C', 'D', 'e', 'f', 'G']

Steve

Try above (untested), noting:
itr = enumerate('abcd ef')
for i,c in itr: ... print i,c
... if c=='d': break
... else:
... print 'first else'
...
0 a
1 b
2 c
3 d for i,c in itr:

... print i,c
... if c=='z': break
... else:
... print '2nd else'
...
4 e
5 f
2nd else

Regards,
Bengt Richter
Jul 18 '05 #5
Pekka Niiranen <pe************ @wlanmail.com> wrote:
...
... try:
... for i, char in itr:
... print 'inner', i, char
... if char == 'f':
... break
... except StopIteration:
... print "f not found" ... Not working: Iter() takes care of its own exceptions?
Nope. Rather, the 'for' statement does not propagate the StopIteration
exception that terminates it -- such a propagation would be extremely
disruptive of 99% of Python's programs, and I'm astonished that you
expected it!

What you want is, I believe, among the Tutorial's examples...:

for i, ch in itr:
print 'inner', i, ch
if ch == 'f': break
else:
print 'f not found'

That's what the 'else' clause in a 'for' statement is for: it triggers
when the loop terminates normally (as opposed to ending with a break or
return or by propagating an exception). The ability to deal with a "not
found" case, where the "found" cases exit by break, is the main use case
of this 'else' clause.
This recurring feeling that writing REALLY correct programs in Python
is not easier than in lower level languages... :(


I think that you can get all the info about Python you need for the
purpose (and then some) from "Python in a Nutshell", but of course I'm
biased...;-)
Alex
Jul 18 '05 #6

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

Similar topics

7
1788
by: Alfonso Morra | last post by:
I have a class that contains a nested class. The outer class is called outer, and the nested class is called inner. When I try to compile the following code, I get a number of errors. It is not obvious to me, where I'm going wrong (the compiler messages do not seem to make much sense). here is the code: outer class declared as ff in "outer.h":
1
1449
by: Rich Parker | last post by:
Hello everyone. I have been using PostgreSQL for about 3-4 years now, it's wonderful how I can make it do things and write Perl programs to interface with it. Since I do all of the DBA behind the scenes on our company Intranet (Linux-Apache based), and I really prefer writing Perl programs to do my simple admin functions. I really like those \d commands (via telnet) and they tell me a lot of what I need for writing new programs etc, but...
3
1772
by: JC Mugs | last post by:
Help needed for project-Access 2002(office xp) PROBLEM: Figuring out how to lookup a record and DDate field in Table1 - Take that DDate-field data from record looked up and assign it to Date field in a new record on a form using Table2. BASIC Table1 Fields: DID -Primary KEY DDate --Information I need to move to new form
3
2317
by: Cliff Harris | last post by:
I have an odd question that I'm hoping someone can help with. I simply (or not simply?) need to enumerate through all of the data types in the .Net framework. I do understand that if this is possible, it will take a long time, and I really don't care :) I need to go through all of the types, look for something within each, and do something with it if it contains what i'm looking for. So, is it possible to do this enumeration? Let me...
6
2030
by: Gregory Petrosyan | last post by:
Hello! I have a question for the developer of enumerate(). Consider the following code: for x,y in coords(dots): print x, y When I want to iterate over enumerated sequence I expect this to work: for i,x,y in enumerate(coords(dots)):
4
1123
by: trevor_morgan | last post by:
The following code: def functions(): l=list() for i in range(5): def inner(): return i l.append(inner) return l
56
5204
by: Zytan | last post by:
Obviously you can't just use a simple for loop, since you may skip over elements. You could modify the loop counter each time an element is deleted. But, the loop ending condition must be checked on each iteration, since the Count changes as you delete elements. I would think it is guaranteed to be computed each time, and not cached. So, is this the best way?
1
1917
by: mjdryden | last post by:
I have a bit of a complicated mix of COM and .Net here, so bear with me while I explain :) We have a Type Library that defines all of the interfaces used in this project (a rather large one at that) which was created in VB6. For a number of unrelated reasons, we've chosen to create new .Net classes that implement these interfaces, which are, for the most part, working correctly. We are able to pass our new objects into our COM classes...
8
9431
by: Perl Beginner | last post by:
I am using Win32. I have created an excel spreadsheet, formatted the columns and rows, and would like to write to the cells…all of this using Spreadsheet::WriteExcel. My issue is, my script is very vast with a lot of subroutines, but I need the excel spreadsheet created in the main subroutine becasue this is where the data is that i want to capture. So if I create and format the spreadsheet within the main subroutine, and as it loops through,...
0
9439
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9882
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
8905
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
7431
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
6690
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
5326
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...
1
3987
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3589
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2832
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.