FIT1008 Lecture Notes - Lecture 7: Init
Iterators
x"="Iterator()
it"="iter(x)
next(it)
[original"class,"in"this"case"LinkedList]
def __iter__(self):
return Iterator(self.head/top/front)
class Iterator:
def __init__(self, head):
self.current = head
def __next__(self):
if self.current is None:
raise StopIteration
else:
item_required = self.current.item
self.current = self.current.next
return item_required
def __iter__(self):
return self
List*comprehensions
Perform"an"op"on"every"element
•
Selecting"a"subset"of"elements"that"meet"a"condition
•
Returning"a"list"afterwards
•
**"must"define"outside"class"-no"access"to"internals
•
def all_positive(a_list):
[eg1.]
return [] == [e for e in a_list if e <= 0]
[eg2.]
positive = [x for x in a_list if x > 0]
print(positive)
Week$7:$iterators,$list$comprehensions
Friday,"15"June"2018
11:25
Document Summary
Iterators x = iterator() it = iter(x) next(it) [original class, in this case linkedlist] def __iter__(self): return iterator(self. head/top/front) class iterator: def __init__(self, head): self. current = head def __next__(self): if self. current is none: raise stopiteration else: item_required = self. current. item self. current = self. current. next return item_required def __iter__(self): return self. Selecting a subset of elements that meet a condition. ** must define outside class - no access to internals def all_positive(a_list): [eg1. ] return [] == [e for e in a_list if e <= 0]