Both generate lists, but they are used differently, so I will summarize them lightly.
One of the common ways to write map-like methods. Python also has a map method, but list comprehensions are faster, so let's use this.
List comprehension
names = ['Alice', 'Bob', 'Carl', 'Dave']
[name[0] for name in names] # => ['A', 'B', 'C', 'D']
map method
names = ['Alice', 'Bob', 'Carl', 'Dave']
map(lambda name: name[0], names) # => ['A', 'B', 'C', 'D']
It can be used when you want to create a new list of elements that meet the conditions from the list. It is possible to write multiple conditions by continuing if, and of course you can also write with and.
names = ['Alice', 'Bob', 'Carl', 'Dave']
[name for name in names if len(name) == 4] # => ['Carl', 'Dave']
[name for name in names if not len(name) == 4] # => ['Alice', 'Bob']
[name for name in words if not len(name) == 4 if len(name) < 5] # => ['Bob']
[name for name in words if not len(name) == 4 and len(name) < 5] # => ['Bob']
You can create a new list from multiple lists at the same time by using zip.
namesA = ['Alice', 'Bob', 'Carl', 'Dave']
namesB = ['Peter', 'Micheal', 'John', 'Harry']
[" ".join([x, y]) for x, y in zip(namesA, namesB)]
# => ['Alice Peter', 'Bob Micheal', 'Carl John', 'Dave Harry']
Multiple loops can be expressed by overlapping for.
namesA = ['Alice', 'Bob', 'Carl', 'Dave']
namesB = ['Peter', 'Micheal', 'John', 'Harry']
[" ".join([x, y]) for x in namesA for y in namesB]
# => ['Alice Peter',
# 'Alice Micheal',
# 'Alice John',
# 'Bob Peter',
# 'Bob Micheal',
# 'Bob John',
# 'Carl Peter',
# 'Carl Micheal',
# 'Carl John',
# 'Dave Peter',
# 'Dave Micheal',
# 'Dave John']
Generators can generate elements from defined expressions. You can retrieve the value from the generator with next.
g = (x ** 2 for x in range(5))
next(g) # => 0
next(g) # => 1
next(g) # => 4
next(g) # => 16
next(g) # StopIteration
You can use a generator to stop generating values when the conditions are met. There are other uses, though.
Bonus itertools
There is a Python module called itertools, which has nicely implemented methods to generate iterators.
For example, when you want to enumerate combinations
import itertools
itertools.combinations('ABCD', 2) # => (A,B) (A,C) (A,D) (B,C) (B,D) (C,D)
Note that this only creates an iterator, not a list.
This is where you can learn such a little notation while solving problems. Udacity Design of computer programming
Blogs doing (or trying to) machine learning with python Effort 1mm blog
Recommended Posts