简体   繁体   English

如何查找列表的交集和并集(不使用集合)

[英]How to find Intersection and Union of a List (without using sets)

I am trying to find the intersection and union of two lists for an assignment, however, I cannot use sets . 我试图找到一个分配的两个列表的交集和并集,但是, 我不能使用set From set theory, an intersection between two sets is the elements that are in both sets. 根据集合论,两个集合之间的交集是两个集合中的元素。 A union is all elements in both sets, without repetition. 联合是两个集合中的所有元素,没有重复。 So far I have: 到目前为止,我有:

setA = [1,2,3,4,5,6,7,8,9]
setB = [1,5,0,9]

def getUnion(a, b):
    return a + b

def getIntersection(a, b):
    return 

My union function is returning duplicates. 我的联合函数返回重复项。 Is there a way to simply find the union? 有没有办法简单地找到工会?

Also, what is the best approach to find the intersection? 另外,找到相交的最佳方法是什么?

Union and intersection without using using sets: 不使用集合的并集和交集:

setA = [1,2,3,4,5,6,7,8,9]
setB = [1,5,0,9]

intersection = [i for i in setA if i in setB]
list_union = list({i: i for i in setA + setB}.values())

print(intersection)
print(list_union)

Output: 输出:

[1, 5, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Explanation : 说明

For union: 对于工会:

[i for i in setA if i in setB]

Simply loops through setA and adds elements that are also found in setB 只需循环遍历setA并添加在setB中也可以找到的setB

For intersection: 对于交叉点:

list({i: i for i in setA + setB}.values())

Creates a dictionary where the keys and values are the result of setA + setB . 创建一个字典,其中的键和值是setA + setB的结果。 Since keys in a dictionary are unique, duplicates don't show up in the final dictionary, and list(dct.values()) is used to pull just the values needed from the dictionary. 由于字典中的键是唯一的,因此最终的字典中不会显示重复项,并且list(dct.values())用于仅从字典中提取所需的值。

So, assume you can use sort . 因此,假设您可以使用sort Sort two lists first, then do with two pointers, move one pointer with smaller value forward each time. 首先对两个列表进行排序,然后使用两个指针,每次向前移动一个值较小的指针。

For union func, add all values each time and move forward both pointers when their values are equal. 对于并集函数,每次都添加所有值,并在两个指针的值相等时向前移动两个指针。 For intersection func, only add values when the values are equal. 对于交集函数,仅当值相等时才添加值。

Time O(nlogn+n)->O(nlogn) 时间O(nlogn + n)-> O(nlogn)

You can use collections.Counter instead to calculate union and intersection 您可以使用collections.Counter代替来计算并集和交集

>>> from collections import Counter

>>> c = Counter(setA + setB)
>>> [a[0] for a in c.items() if a[1] > 1] #Intersection
>>> [1,5,9]

>>> list(c.keys()) #Union
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Counter object hold the data in format: Counter对象以以下格式保存数据:

>>> c
>>> Counter({1: 2, 5: 2, 9: 2, 0: 1, 2: 1, 3: 1, 4: 1, 6: 1, 7: 1, 8: 1})

The key is the elements in the list and the value is the occurrence of the element in the list. 键是列表中的元素,值是列表中元素的出现。

Try this: 尝试这个:

setA = [1,2,3,4,5,6,7,8,9]
setB = [1,5,0,9]

print (list(set(setA).intersection(setB)))

Output: 输出:

[1, 5, 9]
[Finished in 0.0s]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM