gpt4 book ai didi

python - 如何在不使用嵌套 "for"循环的情况下迭代两个列表

转载 作者:行者123 更新时间:2023-11-30 22:55:23 24 4
gpt4 key购买 nike

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

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

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

我尝试这样做:

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

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

最佳答案

你也许可以排成一行来完成!

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

关于python - 如何在不使用嵌套 "for"循环的情况下迭代两个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37444508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com