What is the Matlab equivalent for Python `not in`?

In Python, you can get elements that are exclusive to lst1 using:

 lst1=['a','b','c'] lst2=['c','d','e'] lst3=[] for i in lst1: if i not in lst2: lst3.append(i) 

What will be the equivalent of Matlab?

+5
source share
1 answer

Are you looking for MATLAB setdiff -

 setdiff(lst1,lst2) 

Run Example -

 >> lst1={'a','b','c'}; >> lst2={'c','d','e'}; >> setdiff(lst1,lst2) ans = 'a' 'b' 

Check with Python run -

 In [161]: lst1=['a','b','c'] ...: lst2=['c','d','e'] ...: lst3=[] ...: for i in lst1: ...: if i not in lst2: ...: lst3.append(i) ...: In [162]: lst3 Out[162]: ['a', 'b'] 

In fact, you have setdiff in Python's NumPy module , and numpy.setdiff1d . The equivalent implementation with it will be -

 In [166]: import numpy as np In [167]: np.setdiff1d(lst1,lst2) # Output as an array Out[167]: array(['a', 'b'], dtype='|S1') In [168]: np.setdiff1d(lst1,lst2).tolist() # Output as list Out[168]: ['a', 'b'] 
+13
source

Source: https://habr.com/ru/post/1240532/


All Articles