【问题标题】:How to iterate through two lists without the use of nested "for" loops如何在不使用嵌套“for”循环的情况下遍历两个列表
【发布时间】:2016-05-25 17:59:15
【问题描述】:

如何在不使用嵌套“for”循环的情况下遍历两个列表?

两个列表之间的索引不一定要相同

更具体地说,我正在编写一个函数,该函数采用字符串列表和禁用词列表。如果每个字符串中都有任何被禁止的单词,则整个字符串都会被删除。

我试过了:

for word in bannedWords:
    for string in messages:
        if word in string:
            messages.remove( string )

但是,这不起作用,因为在“for”循环中使用了字符串变量,因此从消息中删除字符串会弄乱“for”循环。有什么更好的实施方式?谢谢。

【问题讨论】:

  • 在我看来你需要嵌套的'for'循环来做你想做的事。您的问题实际上是:“如何在迭代时从列表中删除项目?”。你可以在这里找到一些答案:stackoverflow.com/questions/1207406/…

标签: python python-2.7 for-loop


【解决方案1】:

你可能会在一行中完成!

messages = [string for string in messages 
              if not any(word in bannedWords for word in string)]

【讨论】:

  • x 这里将是一个字母。
  • 这将是一个词。让我来解决这个糟糕的变量命名选择。
  • 不管你怎么命名,遍历一个字符串会给出单个字符。
  • 根据OP的代码,似乎“消息”是一个句子列表,“字符串”是一个单词列表。遍历字符串列表会在每次迭代中给出一个“单词”。
  • 感谢大家的快速回复。 Thrustmaster 的算法似乎运行良好,正是我想要的。一直在为此苦苦挣扎。非常感谢。
【解决方案2】:

我可能会写这样的东西:

def filter_messages(messages, bannedWords):
    for string in messages:
        if all(word not in string for word in bannedWords):
            yield string

现在你有了一个生成器函数,它只会给你很好的消息。如果你真的想原地更新messages,你可以这样做:

messages[:] = filter_messages(messages, bannedWords)

虽然就地要求很少:

messages = list(filter_messages(messages, bannedWords))

【讨论】:

    【解决方案3】:

    假设一组禁用词和一个可能包含这些坏词的字符串列表:

    bannedWords = set("bad", "offensive")
    
    messages = ["message containing a bad word", "i'm clean", "i'm offensive"]
    
    cleaned = [x for x in messages if not any(y for y in bannedWords if y in x)]
    

    结果:

    >>> cleaned
    ["i'm clean"]
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 1970-01-01
      相关资源
      最近更新 更多