2016-09-28 165 views
7

我看到下面的代码可以检查一个词是比较列表字符串字符串列表

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删除'和'?

__________________update___________________

我刚刚发现,做同样的事情没有与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' ...] 

我该怎么做?

+0

重新您的更新,有什么不工作?它是否给出错误?也许你只是不在你的'myPath'变量中使用反斜杠? – brianpck

+0

@brianpck谢谢,我更新了。上面向sys.path添加路径的函数工作不一致。它有时有效,有时不起作用。也许这是我的环境的一个特定问题,我猜...顺便说一句,如果我这样做,将路径添加到sys.path路径列表中,Intersection函数是最好的办法吗? – noclew

+0

如果你想找到两个列表中的路径,那么是的,交集是最好的方法。关于'sys.path',我建议问另一个问题,如果这是一个问题,因为它是一个单独的问题。 – brianpck

回答

8

有一个简单的方法来检查两个列表的交集:将它们转换为一组,并使用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()列表。

+0

非常感谢! – noclew

+0

嗨,布赖恩,我刚刚更新了我的问题。你可以看看它吗? – noclew

1

试一下:

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

只是为了澄清;这是显示'list1'中的单词,*不是'compSet'中的*,而不是其中的单词。 –