为什么我的设定方法在某些情况下有效而在其他情况下失败?

发布于 2025-02-12 06:53:32 字数 1682 浏览 0 评论 0原文

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

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

发布评论

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

评论(2

假面具 2025-02-19 06:53:33

您正在从同一列表中删除项目。

最好是只收集确实匹配的,然后返回这些:

def answer():
    ...
    valid_words = []
    for word in words:
        if ...:
           valid_words.append(word)
    return valid_words

添加几个调试打印件更清楚地显示出来:


In [81]: findWords(['abdfs', 'cccd', 'a', 'qwwewm'])
0: words = ['abdfs', 'cccd', 'a', 'qwwewm'], word=abdfs
removing abdfs: 0
1: words = ['cccd', 'a', 'qwwewm'], word=a
2: words = ['cccd', 'a', 'qwwewm'], word=qwwewm
removing qwwewm: 2
Out[81]: ['cccd', 'a']

它实际上永远不会检查cccd,因为您已经摆弄了列表上下文和迭代器跳过它。

You're removing items from the same list you're iterating over.

Better would be to only collect the ones that do match, and return those:

def answer():
    ...
    valid_words = []
    for word in words:
        if ...:
           valid_words.append(word)
    return valid_words

adding a couple of debugging prints shows this more clearly:


In [81]: findWords(['abdfs', 'cccd', 'a', 'qwwewm'])
0: words = ['abdfs', 'cccd', 'a', 'qwwewm'], word=abdfs
removing abdfs: 0
1: words = ['cccd', 'a', 'qwwewm'], word=a
2: words = ['cccd', 'a', 'qwwewm'], word=qwwewm
removing qwwewm: 2
Out[81]: ['cccd', 'a']

It never actually checks cccd because you've fiddled with the list context and the iterator skips over it.

多像笑话 2025-02-19 06:53:33

您可以通过使用任何()函数与组合列表理解:

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        return [i for i in words if any(all(c in j for c in i.lower()) for j in ['qwertyuiop','asdfghjkl','zxcvbnm'])]

You can solve the problem in one line by using any() function in combination with a composed list comprehension:

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        return [i for i in words if any(all(c in j for c in i.lower()) for j in ['qwertyuiop','asdfghjkl','zxcvbnm'])]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文