简体   繁体   English

将列表中的字符串与列表中的字符串进

[英]comparing strings in list to strings in list

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)

Now I want to check if a word in a list is in some other list as below: 现在我想检查列表中的单词是否在其他列表中,如下所示:

list1 = ['this', 'and', 'that' ]
compSet = [ 'check','that','thing' ]

What's the best way to check if words in list1 are in compSet, and doing something over non-existing elements, eg, appending 'and' to compSet or deleting 'and' from list1? 检查list1中的单词是否在compSet中,以及对非现有元素执行某些操作的最佳方法是什么,例如,将'和'附加到compSet或从list1中删除'和'?

__________________update___________________ __________________update___________________

I just found that doing the same thing is not working with sys.path. 我刚刚发现做同样的事情不适用于sys.path。 The code below sometimes works to add the path to sys.path, and sometimes not. 下面的代码有时会添加到sys.path的路径,有时不会。

myPath = '/some/my path/is here'
if not any( myPath in s for s in sys.path):
    sys.path.insert(0, myPath)

Why is this not working? 为什么这不起作用? Also, if I want to do the same operation on a set of my paths, 另外,如果我想在一组路径上执行相同的操作,

myPaths = [ '/some/my path/is here', '/some/my path2/is here' ...]

How can I do it? 我该怎么做?

There is a simple way to check for the intersection of two lists: convert them to a set and use intersection : 有一种简单的方法可以检查两个列表的交集:将它们转换为集合并使用intersection

>>> list1 = ['this', 'and', 'that' ]
>>> compSet = [ 'check','that','thing' ]
>>> set(list1).intersection(compSet)
{'that'}

You can also use bitwise operators: 您还可以使用按位运算符:

Intersection: 路口:

>>> set(list1) & set(compSet)
{'that'}

Union: 联盟:

>>> set(list1) | set(compSet)
{'this', 'and', 'check', 'thing', 'that'}

You can make any of these results a list using list() . 您可以使用list()将这些结果中的任何一个作为列表。

Try that: 试试看:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM