检查一个数组的元素是否包含在另一个数组中

时间:2016-10-21 08:41:57

标签: arrays python-2.7

**

labels = ['UNREAD', 'CATEGORY_PERSONAL', 'INBOX']
incomingLabels = ['UNREAD','IMPORTANT' 'CATEGORY_PERSONAL', 'INBOX']

**

labels array是静态数组。如何查看incoming array包含labels array的所有元素。

我的尝试

intersectionOfTwoArrays = list(set(incomingLabels) & set(labels))
if np.array_equal(labels, intersectionOfTwoArrays): 
   //Do somthing 

该尝试未成功,因为intersectionOfTwoArrays's未与labels array

订购相同

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

在执行array_equal之前将两个列表转换为set以避免订单问题

labels = ['UNREAD', 'CATEGORY_PERSONAL', 'INBOX']
incomingLabels = ['UNREAD','IMPORTANT', 'CATEGORY_PERSONAL', 'INBOX']
intersectionOfTwoArrays = list(set(incomingLabels) & set(labels))

if np.array_equal(set(labels), set(intersectionOfTwoArrays)): 
    # Do somthing 
    print "match"

或者,您可以使用set method issubset

labels = ['UNREAD', 'CATEGORY_PERSONAL', 'INBOX']
incomingLabels = ['UNREAD','IMPORTANT', 'CATEGORY_PERSONAL', 'INBOX']

if set(labels).issubset(set(incomingLabels)):
    # issubset true, do something
    print "match"