faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 3 people (33%) answered Yes
Recently 0 of 2 people (0%) answered Yes

Entry

Iterator class

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 341, Craig Schardt


"""
Packages: oop
"""
"""
>How about the the mxTools solution:
>
>sum = 0.0
>for x,y in tuples(list1, list2):
>    sum = sum + x*y
This could also be acheived with the following Python class:
"""
class Iter:
    onelist = 0
    def __init__(self, *args):
        if len(args) == 1:
            self.onelist = 1
            self.items = args[0]
        else:
            self.items = args
    def __getitem__(self, index):
        if self.onelist:
            return self.items[index]
        values = []
        for seq in self.items:
            try:
                values.append(seq[index])
            except IndexError:
                values.append(None)
        for val in values:
            if val is not None:
                break
        else:
            raise IndexError
        return tuple(values)
"""
Sorry for the lack of documentation but I just whipped it up. Just
call it as:
for i,j in Iter(list1,list2):
	dosomething(i,j)
"""