【问题标题】:comparing strings in list to strings in list将列表中的字符串与列表中的字符串进行比较
【发布时间】: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,如果这是一个问题,我建议再问一个问题,因为它确实是一个单独的问题。

标签: python list


【解决方案1】:

有一种简单的方法可以检查两个列表的交集:将它们转换为集合并使用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() 将这些结果中的任何一个列成一个列表。

【讨论】:

  • 非常感谢!
  • 嗨,布赖恩,我刚刚更新了我的问题。可以看看吗?
【解决方案2】:

试试看:

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

【讨论】:

  • 澄清一下;这显示了list1 中不在 在compSet 中的单词,而不是其中的单词。
猜你喜欢
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多