Python tricks
2016-10-31
To start reading in lines from a certain line number in Python you can use enumerate and its start
parameter (via)[https://www.youtube.com/watch?v=EnSu9hHGq5o]:
with open('filename.txt') as f:
for linenum, line in enumerate(f, start=10):
# ...
Use a generator to simplify filtering of lines when reading a file:
def interesting_lines(f):
for line in f:
line = line.strip()
if line.startswith('#'):
continue
if not line:
continue
yield line
with open ('filename.txt') as f:
for line in interesting_lines(f):
do_something(line)
The interesting_lines()
function can be tested using a list of strings, it doesn't depend on reading a file.
How to break out of two loops? Make the double loop single:
def range_2d(width, height):
for y in range(height):
for x in range(width):
yield x, y
Make your objects iterable:
class ToDoList:
def __init__(self):
self.tasks = []
def __iter__(self):
for task in self.tasks:
if not task.done:
yield task
def all(self):
return iter(self.tasks)
def done(self):
return (t for t in self.tasks if t.done)
todo = ToDoList()
...
for task in todo:
# ...