Paul D. Kraus wrote:
> I need to scan through a list that contains headers to my table.
> If one of the elements is a tuple and one of the elements of the tuple 
> is "s" set self.sort to the index of the tuple in the header list and 
> then replace the element in header with a two field tuple containing 
> everything that was not 's'.
> 
> Actual code in my working example used to call function ...
> 
> report.set_header( 
> ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max
>  
> Talk','r') ] )
> 
>     def set_header(self,header):
>         list = []
>         for cindex in range(len(header)):
>             if type(()) == type(header[cindex]):
>                 for index in range(len(header[cindex]) ):
>                     if header[cindex][index] == 's':
>                         self.sort = cindex
>                         for tindex in range(len(header[cindex])):
>                             if tindex != index: 
> list.append(header[cindex][tindex])
>                         header[cindex] = tuple(list)
>         self.header = header

You didn't actually ask a question. I assume you are looking for a 
version of this that is less stroke-inducing?

You are doing a lot of work that Python would happily do for you.

To iterate over a sequence h, instead of generating the indexes to h, use
for x in h:
which will return the items of h directly. If you also need the indices, use
for i, x in enumerate(h)

You can test for membership in a sequence with
if i in h:

You can filter a sequence with a list comprehension:
[ x for x in h if x != s ]
creates a new list containing all the elements of h that are not s.

Putting this all together gives this rewrite:

     def set_header(self, header):
         for i, item in enumerate(header):
             if type(item) != type(()):
                 continue

             if 's' in item:
                 self.sort = i
                 header[i] = tuple([x for x in item if x!='s'])

         self.header = header

Note this does change the list passed in, that could be a problem 
depending on if you use it for anything else.

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to