gpt4 book ai didi

python - 如果在值中*未*找到特定的迭代子字符串,如何返回值?

转载 作者:行者123 更新时间:2023-12-01 02:28:24 26 4
gpt4 key购买 nike

我有一个包含排除子字符串的文本文件,我想迭代该文件以检查并返回不带排除子字符串的输入项。

这里我使用 python 2.4,因此下面的代码可以实现此目的,因为 with openany 不起作用。但我必须对子字符串进行硬编码:

工作代码:

def filterJunk(x):
return [i for i in x if not ('I' in i or 'am' in i or '#junk' in i)]

OutPutList = []
for x in InputstringsList:
OutPutList.append(filterJunk(x))

问题:

但是如果我需要排除 n 个子字符串怎么办?显然,我不会在代码中对它们进行硬编码,因此我想要一种替代方法,以便我可以从排除文件中读取每个子字符串并断言最终值不包含相同的内容

如果在值中找不到文本文件中的子字符串,我是否可以返回一个值。

例如

要处理:

InputstringsList = ["Icantbeapart_of_yourlist_asI_am_in_Junk", "youAre", "MeeToooo", "#junk"]

预期输出

OutPutList = ["youAre", "MeeToooo"]

最佳答案

一行(虽然不一定是最好的事情):

[x for x in stringsList if not [e for e in excluded if e in x]]

from itertools import dropwhile
[x for x in stringsList if not list(dropwhile(lambda t: t not in x, excluded))]

关于python - 如果在值中*未*找到特定的迭代子字符串,如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47107125/

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