高级 Python 列表理解

发布于 2024-08-26 06:55:44 字数 434 浏览 7 评论 0原文

给定两个列表:

chars = ['ab', 'bc', 'ca']
words = ['abc', 'bca', 'dac', 'dbc', 'cba']

如何使用列表推导式通过以下条件生成过滤的 words 列表:假定每个单词的长度为 nchars< /code> 的长度也是 n,过滤后的列表应仅包含每个 i 个字符位于第 i 个字符中的单词words 中的字符串。

在这种情况下,我们应该得到 ['abc', 'bca'] 结果。

(如果这对任何人来说都很熟悉,这是之前 Google Code Jam 中的问题之一)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

夏花。依旧 2024-09-02 06:55:44
>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
>>> [word for word in words if all(l in chars[i] for i, l in enumerate(word))]
['abc', 'bca']
耳钉梦 2024-09-02 06:55:44
[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
[w for w in words if all([w[i] in chars[i] for i in range(len(w))])]
恍梦境° 2024-09-02 06:55:44

使用 zip:

[w for w in words if all([a in c for a, c in zip(w, chars)])]

或使用 enumerate:

[w for w in words if not [w for i, c in enumerate(chars) if w[i] not in c]]

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]]
人│生佛魔见 2024-09-02 06:55:44

使用 index 可以正常工作:

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

我错过了什么吗?

This works, using index:

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

Am I missing something?

没企图 2024-09-02 06:55:44

更简单的方法:

yourlist = [ w for w in words for ch in chars if w.startswith(ch) ]

A more simple approach:

yourlist = [ w for w in words for ch in chars if w.startswith(ch) ]
鼻尖触碰 2024-09-02 06:55:44

为什么这么复杂?这也有效:

[words[x] for x in range(len(chars)) if chars[x] in words[x]]

Why so complex? This works as well:

[words[x] for x in range(len(chars)) if chars[x] in words[x]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文