[Tutor] Working with lines from file and printing to another keeping sequential order

spir denis.spir at free.fr
Tue Apr 28 10:16:51 CEST 2009


Le Mon, 27 Apr 2009 23:29:13 -0400,
Dan Liang <danliang20 at gmail.com> s'exprima ainsi:

> Hi Bob, Shantanoo, Kent, and tutors,
> 
> Thank you Bob, Shantanoo, Kent for all the nice feedback. Exception
> handling, the concept of states in cs, and the use of the for loop with
> offset helped a lot. Here is the code I now have, based on your suggestions,
> and it does what I need:
> 
> ListLines = [ line.rstrip() for line in open('test.txt') ]
> 
> countYes = 0
> countNo = 0
> 
> for i in range(len(ListLines)):
>  if ListLines[i].endswith('yes'):
>      countYes+=1
>      print "countYes", countYes, "\t\t", ListLines[i]
> 
>  if not ListLines[i].endswith('yes'):
>     continue
> 
>  for offset in (1, 2, 3, 4, 5, 6, 7, 8):
>     if i+offset < len(ListLines) and ListLines[i+offset].endswith('no'):
> 
>        countNo+=1
> 
>        print "countNo", countNo, "\t\t", ListLines[i+offset]

It probably works, but there is something uselessly complicated, logically speaking:
-1- case ends with 'yes', do
-2- case not ends with 'yes', do
-3- case ends with 'yes', again, do

You'd better group -1- and -3-, no? Moreover, as action -2- is to continue, further code is simplified if -2- is placed first:

for i in range(len(ListLines)):
  if not ListLines[i].endswith('yes'):
    continue
  # case line ends with 'yes': process it
  countYes+=1
  print "countYes", countYes, "\t\t", ListLines[i]
  for offset in (1, 2, 3, 4, 5, 6, 7, 8):
    if i+offset < len(ListLines) and ListLines[i+offset].endswith('no'):
      countNo+=1
      print "countNo", countNo, "\t\t", ListLines[i+offset]

Also, use more than 1 space for indent, and be consistent (set the value in your editor settings and use the TAB key to achieve that); and avoid too many useless blank lines.

Denis
------
la vita e estrany


More information about the Tutor mailing list