【发布时间】:2016-09-28 20:32:09
【问题描述】:
我看到下面的代码可以检查一个单词是否是
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' ...]
我该怎么做?
【问题讨论】:
-
重新更新,什么不起作用?它给出错误吗?也许您只是没有在
myPath变量中使用反斜杠? -
@brianpck 谢谢,我更新了。上面添加路径到 sys.path 的函数工作不一致。它有时有效,有时无效。也许这是我的环境的一个特定问题,我猜......顺便说一句,如果我这样做添加到路径列表中的路径列表与 sys.path,交集函数是最好的吗?
-
如果你想找到两个列表中的路径,那么是的,交叉是最好的方法。关于
sys.path,如果这是一个问题,我建议再问一个问题,因为它确实是一个单独的问题。