我看到下面的代码可以检查一个词是否是
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()
将这些结果中的任何一个制成列表。
关于python - 将列表中的字符串与列表中的字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39757126/