wiki:python/List comprehension

see list?


Python Tutorial


Python List Comprehensions: Explained Visually


Examples

List of dictionaries

Re: Datenstruktur eines dict() importieren

>>> TEMPLATE = [
... ('product', str),
... ('price', float),
... ('stock', int)
... ]
>>> data = [['Milk', '0.99', '24'], ['Bread', '3.79', '8']]
>>> products = [
... dict((k, f(v)) for ((k, f), v) in zip(TEMPLATE, row)) for row in data
... ]
>>> products
[{'product': 'Milk', 'price': 0.98999999999999999, 'stock': 24}, {'product': 'Bread', 'price': 3.79, 'stock': 8}]

Split date args

>>> date_args = ['sep/9', '12.04.' '2012/9/18']
>>> [cutted_arg for arg in date_args for cutted_arg in re.split(r'[./]', arg)]
['sep', '9', '12', '04', '2012', '9', '18']

Equivalent to:

>>> date_args = ['sep/9', '12.04.' '2012/9/18']
>>> result = []
>>> for arg in date_args:
...     for cutted_arg in re.split(r'[./]', arg):
...         result.append(cutted_arg)
... 
>>> result
['sep', '9', '12', '04', '2012', '9', '18']

Flatten nested lists

Making a flat list out of list of lists in Python

>>> nested = [[1, 2, 3], [4], [5, 6]]
>>> [item for sublist in nested for item in sublist]
[1, 2, 3, 4, 5, 6]

Equivalent to (more about performance see link above!):

>>> sum(nested, [])
[1, 2, 3, 4, 5, 6]
>>> reduce(lambda x,y: x+y,l)
[1, 2, 3, 4, 5, 6]
>>> list(itertools.chain.from_iterable(nested))
[1, 2, 3, 4, 5, 6]

Remove duplicates

Re: Doppelte Elemente aus zwei Listen entfernen

>>> first = ['A','B','C','D']
>>> second = ['B','C','E']
>>> [e for e in second if e not in first]
['E']

Equivalent to:

>>> first = ['A','B','C','D']
>>> second = ['B','C','E']
>>> set(second) - set(first)
set(['E'])

Permutation

Generator vs List-Comprehension vs while-Schleife...

>>> [[d, m, y] for d in [1, 2, 3] for m in [4, 5] for y in [2010, 2011]]
[[1, 4, 2010], [1, 4, 2011], [1, 5, 2010], [1, 5, 2011], [2, 4, 2010], [2, 4, 2011], [2, 5, 2010], [2, 5, 2011], [3, 4, 2010], [3, 4, 2011], [3, 5, 2010], [3, 5, 2011]]


Four Tricks for Comprehensions in Python
Bekomme LC nicht hin...
Zeit - Schleife
Dictionary mit Platzhaltern durchsuchen

Last modified 3 years ago Last modified on Dec 2, 2015, 6:15:19 AM