什么是Matlab相当于Python的`not in`?

时间:2016-01-13 13:48:26

标签: python matlab

在Python中,可以使用以下内容获取lst1独有的元素:

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

Matlab的等价物是什么?

1 个答案:

答案 0 :(得分:13)

您正在寻找MATLAB' setdiff -

setdiff(lst1,lst2)

示例运行 -

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

使用Python运行验证 -

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']

事实上,您在NumPy module numpy.setdiff1d中也有setdiffenter image description here。与它等效的实现将是 -

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']