比较list中的字符串和list中的字符串



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

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中,并对不存在的元素做一些事情,例如,在compSet中添加'和'或从list1中删除'和',最好的方法是什么?

__________________ 更新 ___________________

我刚刚发现做同样的事情不工作与sys.path。下面的代码有时可以为sys添加路径。路径,有时不是。

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()将这些结果中的任何一个制作成列表。

试试:

 >>> l = list(set(list1)-set(compSet))
 >>> l
 ['this', 'and']

最新更新