Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不使用嵌套“的情况下遍历两个列表”;至于;循环_Python_Python 2.7_For Loop - Fatal编程技术网

Python 如何在不使用嵌套“的情况下遍历两个列表”;至于;循环

Python 如何在不使用嵌套“的情况下遍历两个列表”;至于;循环,python,python-2.7,for-loop,Python,Python 2.7,For Loop,如何在不使用嵌套的“for”循环的情况下遍历两个列表 两个列表之间的索引不一定必须相同 更具体地说,我正在编写一个函数,该函数包含一个字符串列表和一个禁用字列表。如果每个字符串中都有任何被禁止的单词,则整个字符串将被删除 我试着做: for word in bannedWords: for string in messages: if word in string: messages.remove( string ) 但是,这不起作用,因为字符串

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

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

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

我试着做:

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

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

我可能会这样写:

def filter_messages(messages, bannedWords):
    for string in messages:
        if all(word not in string for word in bannedWords):
            yield string
现在你有了一个生成器功能,它只会给你好消息。如果您确实想就地更新
消息
,可以执行以下操作:

messages[:] = filter_messages(messages, bannedWords)
虽然现场要求很少:

messages = list(filter_messages(messages, bannedWords))

你可以排成一行来做

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

假设一组被禁止的单词和一组可能包含这些坏单词的字符串:

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"]
>>> 

x
这里只有一个字母,应该是一个单词。让我来修复这个糟糕的变量命名选择。不管你如何命名,对字符串进行迭代都会产生单个字符。根据OP的代码,“消息”似乎是一个句子列表,“字符串”是一个单词列表。在字符串列表上迭代会在每次迭代中给出一个“单词”。感谢各位的快速响应。推力器大师的算法似乎工作完美,正是我所寻找的。我已经为此挣扎了一段时间。非常感谢。在我看来,您需要嵌套的“for”循环来执行您想要的操作。您的问题实际上是:“如何在迭代列表时从列表中删除项目?”。你可以在这里找到一些答案: