python - 将列表中的字符串与列表中的字符串进行比较

标签 python 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 中以及对不存在的元素执行某些操作(例如,将“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/

相关文章:

python - 将一列中的非数字转换为 pandas 中的 nan

python - 列表理解表达式错误中的 List remove() 方法

arrays - lapply 适用于数组还是单个元素?

python - 搜索并添加 python 列表

python - 如何使用数据透视表 Python 创建重复行

java - Python 可以识别 Java 中使用 BCrypt 的哈希密码吗?

java - java中优化的线程安全列表

python - 如何将子列表拆分为k次子列表? (Python)

java - 如何用 N 个分区而不是大小为 N 的分区对列表进行分区?

python - numpy 的 CSV 过滤