Advanced Python list comprehension

2019-04-05 23:04发布

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条回答
Deceive 欺骗
2楼-- · 2019-04-05 23:45
[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
查看更多
太酷不给撩
3楼-- · 2019-04-05 23:51

This works, using index:

[words[chars.index(char)] for char in chars if char in words[chars.index(char)]]

Am I missing something?

查看更多
戒情不戒烟
4楼-- · 2019-04-05 23:51

A more simple approach:

yourlist = [ w for w in words for ch in chars if w.startswith(ch) ]
查看更多
smile是对你的礼貌
5楼-- · 2019-04-05 23:51

Why so complex? This works as well:

[words[x] for x in range(len(chars)) if chars[x] in words[x]]
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-04-05 23:57
>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
查看更多
一夜七次
7楼-- · 2019-04-06 00:01

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]]
查看更多
登录 后发表回答