Friday, 1 May 2015

misc python

python stuff:

I started writing python as a sort of souped up bash - an improvement but not ideal.

some of the really cool features in python are iterators/generators

lists are iterable:

>>> myl = ['a','b','c']
>>> for let in myl:
...     print let
>>> # generators are similar to iterators but you can iterate over them only once.
>>> myg = (x*x for x in range(5))
>>> for i in myg:
...     print i
>>> for i in myg:
...     print i
>>>#  nothing the second time

yield is similar to return - except it returns a generator:

def getdata(fp):
    for line in fp:
        if not line.startswith('#'):
            yield line

with open("/etc/hosts","r") as fp:
    longest = max(get_lines(fp), key=len)  # this bit is where the funkiness comes in!
    print longest

uses less memory, faster - but can also act on the result how we want.

No comments:

Post a Comment

bash best practices

Bash best practices A few hints on bash best practice: * use #!/usr/bin/env bash .. this is more portable but you cant rely on a spe...