Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advanced Python list comprehension

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)

like image 951
Yuval Adam Avatar asked Mar 26 '10 10:03

Yuval Adam


People also ask

What is faster than list comprehension Python?

For loops are faster than list comprehensions to run functions.

Are list comprehensions good practice?

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!).

What is advanced list processing in Python?

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.

Is list comprehension faster than lambda?

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.


3 Answers

>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
like image 102
SilentGhost Avatar answered Sep 25 '22 02:09

SilentGhost


[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
like image 32
Marcelo Cantos Avatar answered Sep 24 '22 02:09

Marcelo Cantos


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]]
like image 31
flight Avatar answered Sep 23 '22 02:09

flight