我需要验证一个列表是否是另一个列表的子集-布尔返回是我所寻求的。

在交叉路口后的小列表上测试相等性是最快的方法吗?考虑到需要比较的数据集的数量,性能是极其重要的。

在讨论的基础上补充进一步的事实:

对于许多测试,这两个列表是否都是相同的?其中一个是静态查找表。 需要是一个列表吗?它不是——静态查找表可以是任何性能最好的表。动态的是一个字典,我们从中提取键来执行静态查找。

在这种情况下,最佳解决方案是什么?


当前回答

集合理论不适用于列表,因为重复使用集合理论会导致错误的答案。

例如:

a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
set(b) > set(a)

没有任何意义。是的,它给出了一个错误的答案,但这是不正确的,因为集合理论只是比较:1,3,5与1,3,4,5。你必须包括所有副本。

相反,你必须计算每一项的出现次数,并使用大于等于来检查。这不是很昂贵,因为它不使用O(N²)操作,也不需要快速排序。

#!/usr/bin/env python

from collections import Counter

def containedInFirst(a, b):
  a_count = Counter(a)
  b_count = Counter(b)
  for key in b_count:
    if a_count.has_key(key) == False:
      return False
    if b_count[key] > a_count[key]:
      return False
  return True


a = [1, 3, 3, 3, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)

a = [1, 3, 3, 3, 4, 4, 5]
b = [1, 3, 3, 4, 5]
print "b in a: ", containedInFirst(a, b)

然后运行这个,你会得到:

$ python contained.py 
b in a:  False
b in a:  True

其他回答

下面是我如何知道如果一个列表是另一个列表的子集,在我的情况下,序列对我很重要。

def is_subset(list_long,list_short):
    short_length = len(list_short)
    subset_list = []
    for i in range(len(list_long)-short_length+1):
        subset_list.append(list_long[i:i+short_length])
    if list_short in subset_list:
        return True
    else: return False

如果我迟到了,请原谅。;)

为了检查集合A是否是集合B的子集,Python有a.is子集(B)和A <= B。它只对集合起作用,而且工作得很好,但内部实现的复杂性是未知的。参考:https://docs.python.org/2/library/sets.html #集对象

我提出了一种算法来检查列表A是否是列表B的子集。

To reduce complexity of finding subset, I find it appropriate to sort both lists first before comparing elements to qualify for subset. It helped me to break the loop when value of element of second list B[j] is greater than value of element of first list A[i]. last_index_j is used to start loop over list B where it last left off. It helps avoid starting comparisons from the start of list B (which is, as you might guess unnecessary, to start list B from index 0 in subsequent iterations.) Complexity will be O(n ln n) each for sorting both lists and O(n) for checking for subset. O(n ln n) + O(n ln n) + O(n) = O(n ln n). Code has lots of print statements to see what's going on at each iteration of the loop. These are meant for understanding only.

检查一个列表是否是另一个列表的子集

is_subset = True;

A = [9, 3, 11, 1, 7, 2];
B = [11, 4, 6, 2, 15, 1, 9, 8, 5, 3];

print(A, B);

# skip checking if list A has elements more than list B
if len(A) > len(B):
    is_subset = False;
else:
    # complexity of sorting using quicksort or merge sort: O(n ln n)
    # use best sorting algorithm available to minimize complexity
    A.sort();
    B.sort();

    print(A, B);

    # complexity: O(n^2)
    # for a in A:
    #   if a not in B:
    #       is_subset = False;
    #       break;

    # complexity: O(n)
    is_found = False;
    last_index_j = 0;

    for i in range(len(A)):
        for j in range(last_index_j, len(B)):
            is_found = False;

            print("i=" + str(i) + ", j=" + str(j) + ", " + str(A[i]) + "==" + str(B[j]) + "?");

            if B[j] <= A[i]:
                if A[i] == B[j]:
                    is_found = True;
                last_index_j = j;
            else:
                is_found = False;
                break;

            if is_found:
                print("Found: " + str(A[i]));
                last_index_j = last_index_j + 1;
                break;
            else:
                print("Not found: " + str(A[i]));

        if is_found == False:
            is_subset = False;
            break;

print("subset") if is_subset else print("not subset");

输出

[9, 3, 11, 1, 7, 2] [11, 4, 6, 2, 15, 1, 9, 8, 5, 3]
[1, 2, 3, 7, 9, 11] [1, 2, 3, 4, 5, 6, 8, 9, 11, 15]
i=0, j=0, 1==1?
Found: 1
i=1, j=1, 2==1?
Not found: 2
i=1, j=2, 2==2?
Found: 2
i=2, j=3, 3==3?
Found: 3
i=3, j=4, 7==4?
Not found: 7
i=3, j=5, 7==5?
Not found: 7
i=3, j=6, 7==6?
Not found: 7
i=3, j=7, 7==8?
not subset

下面的代码检查一个给定的集合是否是另一个集合的“适当子集”

 def is_proper_subset(set, superset):
     return all(x in superset for x in set) and len(set)<len(superset)
>>> a = [1, 3, 5]
>>> b = [1, 3, 5, 8]
>>> c = [3, 5, 9]
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

>>> a = ['yes', 'no', 'hmm']
>>> b = ['yes', 'no', 'hmm', 'well']
>>> c = ['sorry', 'no', 'hmm']
>>> 
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

使用set.issubset

例子:

a = {1,2}
b = {1,2,3}
a.issubset(b) # True
a = {1,2,4}
b = {1,2,3}
a.issubset(b) # False

Python为此提供的性能函数是set. is子集。然而,它确实有一些限制,不清楚它是否能回答你的问题。

一个列表可以多次包含项目,并具有特定的顺序。而一组则不是。此外,set只适用于可哈希对象。

您是在询问子集还是子序列(这意味着您将需要字符串搜索算法)?对于许多测试,这两个列表是否都是相同的?列表中包含哪些数据类型?就此而言,它需要是一个列表吗?

你的另一篇文章交叉了字典和列表,使类型更清晰,并建议使用字典键视图来实现类似于集合的功能。在这种情况下,它是可以工作的,因为字典键的行为类似于集合(以至于在Python中有集合之前,我们使用字典)。人们不禁要问,为什么这个问题在三个小时内变得不那么具体了。