【问题标题】:How to iterate a list of words, and print all words not containing any char of a substring?如何迭代单词列表,并打印所有不包含子字符串任何字符的单词?
【发布时间】:2022-09-23 01:30:22
【问题描述】:

目标是打印出文本文件中不包含子字符串中任何字符的所有单词。

我目前的解决方案是:

words = open(\'words.txt\')

def avoids(fin, letter):
    for line in fin:
        for char in letter:
            if char in line:
                break
            print(line.strip())

avoids(words, \'abo\')

输出是: 芽孢杆菌 芽孢杆菌 是 贝比鲁 比比鲁斯 血腥 有血有肉的 血腥的 血腥

它避免了所有单词一个但仍然打印所有单词b和○.我知道我的错误与第二个循环的中断有关,但我只是无法发现它。

  • 尝试使用 continue 而不是 break。这将进入下一次迭代而不是停止它。
  • minimal reproducible example 将包含一个单词列表,而不是使用我们没有(也不想要)的文件。
  • 尽量减少问题和看(打印)你的程序流程。例如,您可以将print(line.strip()) 替换为print(letter) 并在包含两个或三个单词的列表上执行外循环,或者仅在range 中执行外部循环,而不使用if。

标签: python


【解决方案1】:

您可以创建一个列表理解,检查每个字母是否在单词中。如果列表中没有 True 值,请保留该词。

def avoids(fin, letters):
    to_keep = []
    
    for line in fin:
        if not any([True for l in letters if l in line]):
            to_keep.append(line)
            
    return to_keep

avoids(['google', 'stackoverflow', 'reddit'], 'abc')

>>> ['google', 'reddit']

【讨论】:

  • 试试any。
  • @KellyBundy 确实更好,谢谢。编辑了我的答案。
猜你喜欢
  • 1970-01-01
  • 2010-09-19
  • 2015-11-21
  • 2018-05-06
  • 2016-04-07
  • 2016-02-24
  • 1970-01-01
  • 2015-07-30
相关资源
最近更新 更多