如何在Python中搜索字符串中的列表项?

2024-09-26 22:51:15 发布

您现在位置:Python中文网/ 问答频道 /正文

urlList = ["https://google.com","https://google.com/help","https://facebook.com","https://facebook.com/help","https://facebook.com/test"]

filterKeys = ["help","test"]

clearUrl = []

for i in urlList:
   if filterKeys not in i:  #TypeError: 'in <string>' requires string as left operand, not list
      clearUrl.append(i)

预期输出['https://google.com','https://facebook.com']

多谢各位


Tags: inhttpstestcomforstringfacebookif
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:15

出现此错误是因为您以错误的方式使用了in运算符:

in的工作原理如下:

"string" in <collection>

代码中的问题在于您使用了:

<collection> in "string"

请尝试:

for i in urlList:
    if not any(map(lambda fk: fk in i, filterKeys)):
        # any will return True if at least of one the filterKeys is substring of i
        clearUrl.append(i)    

相关问题 更多 >

    热门问题