Friday, 23 May 2008

Comprehensions - List and Dict

List Comprehensions

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> [i for i in numbers]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> [i for i in numbers if i % 2 == 0]
[2, 4, 6, 8]

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f']
>>> [i for i in letters]
['a', 'b', 'c', 'd', 'e', 'f']
>>> [i for i in letters if i < 'c'] ['a', 'b'] >>> words = ['cow', 'banana', 'boat', 'moat', 'float', 'wrote']
>>> [i for i in words]
['cow', 'banana', 'boat', 'moat', 'float', 'wrote']
>>> [i for i in words if i.count('oat')]
['boat', 'moat', 'float']

>>> sentence = 'The quick brown fox jumped over the lazy cow!'
>>> [word for word in sentence.split() if word.count('a') or word.count('x')]
['fox', 'lazy']

Generator Expressions
>>> stuff = [1, 2, 3, 'cow']
>>> res = (x for x in stuff)
>>> type(res)

Dictionary Comprehension's
>>> tmp = ['a','b','c']
>>> d = dict((x, x*2) for x in tmp)
>>> d
{'a': 'aa', 'c': 'cc', 'b': 'bb'}

>>> d = dict((x, x*2) for x in range(5))
>>> d
{0: 0, 1: 2, 2: 4, 3: 6, 4: 8}

>>> tmp = ['a','b','c']
>>> d = dict((x[0], x[1]*2) for x in enumerate(tmp))
>>> d
{0: 'aa', 1: 'bb', 2: 'cc'}




No comments: