Given two lists:
chars = ['ab', 'bc', 'ca']
words = ['abc', 'bca', 'dac', 'dbc', 'cba']
how can you use list comprehensions to generate a filtered list of words
by the following condition: given that each word is of length n
and chars
is of length n
as well, the filtered list should include only words that each i
-th character is in the i
-th string in words
.
In this case, we should get ['abc', 'bca']
as a result.
(If this looks familiar to anyone, this was one of the questions in the previous Google code jam)
For loops are faster than list comprehensions to run functions.
List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop. While list comprehensions are not the most difficult concept to grasp, it can definitely seem unintuitive at first (it certainly was for me!).
It creates a new list in which each element is the result of applying a given operation in a list. It consists of brackets containing an expression followed by a “for” clause, then a list. The list comprehension always returns a result list.
Graphical representation of list comprehension vs lambda + filter. As we can see from the graph that overall list comprehension is much faster than the filter function.
>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
Using zip:
[w for w in words if all([a in c for a, c in zip(w, chars)])]
or using enumerate:
[w for w in words if not [w for i, c in enumerate(chars) if w[i] not in c]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With