将列表中的字符串与另一个列表中的字符串进行比较

7

I see that the code below can check if a word is

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' ]

如何最好地检查列表1中的单词是否在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' ...]

我该如何做到这一点?


关于您的更新,有什么问题?它是否出现错误?也许您只是没有在myPath变量中使用反斜杠? - brianpck
@brianpck 谢谢,我已经更新了。上面的函数用于将路径添加到sys.path中的工作不一致。有时它有效,有时则无效。也许这是我的环境特定问题,我猜测...顺便说一下,如果我使用sys.path对路径列表进行添加,那么Intersection函数是最好的选择吗? - noclew
如果你想找到两个列表中都存在的路径,那么交集是最好的方法。关于 sys.path,如果这是一个问题,我建议提出另一个问题,因为它实际上是一个独立的问题。 - brianpck
2个回答

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

非常感谢您! - noclew
嗨 Brian,我刚更新了我的问题。你能看一下吗? - noclew

1

Try that:

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

仅澄清一下;这是显示在list1不在 compSet中的单词,而不是其中的单词。 - Ted Klein Bergman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接