Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing strings in list to strings in list

Tags:

python

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?

__________________update___________________

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?

like image 599
noclew Avatar asked Sep 28 '16 20:09

noclew


2 Answers

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)
{'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().

like image 89
brianpck Avatar answered Nov 09 '22 18:11

brianpck


Try that:

 >>> l = list(set(list1)-set(compSet))
 >>> l
 ['this', 'and']
like image 20
coder Avatar answered Nov 09 '22 17:11

coder