我需要在列表上使用is子集()和difference(),但是我不能用集合来翻译我的列表,因为我的列表有重复的,而且它们非常重要。举个例子,我
list1 = [33, 33, 100, 102,]
list2 = [33, 33, 33, 33]
list3 = [99, 100, 101, 102, 103]
list4 = [100,101,102,103,104]我需要知道list1包含在list2中,我需要33,33才能使list1等同于list2,或者list1包含在list3和list4中。
我试过用多个“for循环”来实现它,但我似乎无法正确地完成它
发布于 2022-03-15 01:34:27
所以,很可能,您是在描述一个多集。因此,collections.Counter对象可以作为一个多集。考虑:
>>> list1 = [33, 33, 100, 102,]
>>> list2 = [33, 33, 33, 33]
>>> from collections import Counter然后你可以使用:
>>> Counter(list2) - Counter(list1)
Counter({33: 2})如果你需要一份清单,那么:
>>> list((Counter(list2) - Counter(list1)).elements())
[33, 33]但我怀疑您应该一直使用Counter对象。
>>> c1 = Counter(list1)
>>> c2 = Counter(list2)
>>> diff = c2 - c1
>>> if diff == c2:
... print("none of the elements of list1 are in list2")
... else:
... print("some of the elements of list1 are in list2")
... print("the missing elements are:", list(diff.elements()))
...
some of the elements of list1 are in list2
the missing elements are: [33, 33]发布于 2022-03-15 01:33:07
使用collections.Counter。您可以使用Counter执行在集合上定义的许多操作,具有直观的结果(尽管对于一些需要Python3.10的操作来说)。例如:
list((Counter(list2) - Counter(list1)).elements())
# => [33, 33] (difference)
Counter(list2) <= Counter(list1)
# => False (list2 is not contained in list1)如果您没有Python3.10,则后者将无法工作,因此需要一个解决方案。例如:
def issubcounter(smaller, bigger):
return bool((bigger - smaller) and not (smaller - bigger))
issubcounter(Counter(list2), Counter(list1))
# => False (list2 is not contained in list1)发布于 2022-03-15 01:31:03
当将列表的元素解释为set时,如果列表a的所有元素都包含在list b中,则可以使用这样的定义: list a是list b的子集。如果不希望使用显式for循环检查此属性,请创建列表理解[x for x in a if x not in b]以查找使此属性无效的元素。
为了说明重复(但不是订单),我需要更多的东西,而且我不认为仅仅通过理解就可以做到这一点。
def missing_in(sub, of):
if not sub:
return of
if sub[0] not in of:
return missing_in(sub[1:], of)
ind = of.index(sub[0])
return missing_in(sub[1:], of[:ind]+of[ind+1:])这会在sub中找到of中缺少的元素:如果sub为空,则每个元素都丢失。如果sub的第一个元素在of中完全缺失,我们将忽略它(如果您想要对称的差异,请将它添加到这里的返回列表中)。如果它存在,元素将从sub和of中删除一次,我们可以继续使用sub的下一个元素。可以定义子(多)集的概念,即of可能包含sub中缺少的一些元素,而不是相反的。
def proper_submultiset_of(sub, of):
return len(missing_in(sub, of)) > 0 and not missing_in(of, sub)
def submultiset_of(sub, of):
return not missing_in(of, sub)不过,我不知道[33, 33, 100, 102,]是如何包含在[99, 100, 101, 102, 103]中的。
https://stackoverflow.com/questions/71475998
复制相似问题