views:

309

answers:

3

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)

+6  A: 
[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
Marcelo Cantos
+9  A: 
>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
SilentGhost
+1  A: 

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]]
flight