比较列表中的字符串和列表中的字符串

我看到下面的代码可以检查单词是否为

list1 = 'this'
compSet = [ 'this','that','thing' ]
if any(list1 in s for s in compSet): print(list1)

现在,我想检查列表中的单词是否在其他列表中,如下所示:

list1 = ['this', 'and', 'that' ]
compSet = [ 'check','that','thing' ]

检查list1中的单词是否在compSet中并在不存在的元素上执行某些操作的最佳方法是什么,例如,将“ and”附加到compSet或从list1中删除“ and”?

__________________更新___________________

我只是发现做同样的事情在sys.path中不起作用。下面的代码有时可以将路径添加到sys.path,有时不能。

myPath = '/some/my path/is here'
if not any( myPath in s for s in sys.path):
    sys.path.insert(0, myPath)

为什么这不起作用?另外,如果我想对一组路径执行相同的操作,

myPaths = [ '/some/my path/is here', '/some/my path2/is here' ...]

我该怎么做?

布赖恩普克

有一种简单的方法来检查两个列表的交集:将它们转换为集合并使用intersection

>>> list1 = ['this', 'and', 'that' ]
>>> compSet = [ 'check','that','thing' ]
>>> set(list1).intersection(compSet)
{'that'}

您还可以使用按位运算符:

路口:

>>> set(list1) & set(compSet)
{'that'}

联盟:

>>> set(list1) | set(compSet)
{'this', 'and', 'check', 'thing', 'that'}

您可以使用将这些结果中的任何一个作为列表list()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章