noclew noclew - 1 year ago 71
Python Question

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, e.g., appending 'and' to compSet or deleting 'and' from list1?


I just found that doing the same thing is not working with sys.path. The code below sometimes works to add the path to sys.path, and sometimes not.

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?

Answer Source

There is a simple way to check for the intersection of two lists: convert them to a set and use intersection:

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

You can also use bitwise operators:


>>> set(list1) & set(compSet)


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

You can make any of these results a list using list().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download