Posts: 75
Threads: 29
Joined: Feb 2020
Hi
Is it possible to take the union and the intersection of lists. If affirmative, which module contains these methods, and where to find it ?
Thank you for the advice
Arbiel
Posts: 8,160
Threads: 160
Joined: Sep 2016
what exactly union and intersect would do on lists? Usisally these are terms applied to sets. Provide sample input and desired output
Posts: 75
Threads: 29
Joined: Feb 2020
Yes, those terms apply to mathematical entities, with the following meaning :
Quote:list1=['a', 'b']
list2=['c']
union (list1, list2) : ['a', 'b, 'c']
intersection (list1, list2) : []
>>> dia
['Dasia', 'Dialytika', 'Macron', 'Oxia', 'Perispomeni', 'Prosgegrammeni', 'Psili', 'Tonos', 'Varia', 'Vrachy', 'Ypogegrammeni']
>>> mots
['Greek', 'Small', 'Letter', 'Upsilon', 'with', 'Dialytika', 'and', 'Oxia']
>>> Quote:intersection (dia,mots) : ['Dialytika', 'Oxia']
Arbiel
Posts: 8,160
Threads: 160
Joined: Sep 2016
Mar-27-2020, 08:21 PM
(This post was last modified: Mar-27-2020, 08:21 PM by buran.)
List and sets are different types in python. Sets hold unique/non-repeating elements, while lists can have repeating elements and there comes the tricky part.
As I said union and intersection are terms for sets. There is list.extend() method and for "intersection" you need to use list comprehension or loop
dia = ['Dasia', 'Dialytika', 'Macron', 'Oxia', 'Perispomeni', 'Prosgegrammeni', 'Psili', 'Tonos', 'Varia', 'Vrachy', 'Ypogegrammeni']
mots = ['Greek', 'Small', 'Letter', 'Upsilon', 'with', 'Dialytika', 'and', 'Oxia']
# convert to sets
result = set(dia).union(set(mots))
print(result)
print(list(result))
result2 = set(dia).intersection(set(mots))
print(result2)
print(list(result2))
# if order is imporatnt
result = [element for element in dia if element in set(mots)]
print(result)
dia.extend(mots)
print(dia)
Posts: 75
Threads: 29
Joined: Feb 2020
Hi buran
Thank you for your help. This exactly what I am looking for.
However I do not understand
Quote:you need to use list comprehension or loop
when I see that
result2 = set(dia).intersection(set(mots)) leads to the intersection of the sets.
Arbiel
Posts: 8,160
Threads: 160
Joined: Sep 2016
This is one way to do it
# convert to sets
result = set(dia).union(set(mots))
print(result)
print(list(result))
result2 = set(dia).intersection(set(mots))
print(result2)
print(list(result2)) However, this will not preserve order and set have unique elements, so if there are duplicates in the list (same element more than one time in list) they will be lost
And this is working with lists - order and repeating elements are preserved
# if order is imporatnt
result = [element for element in dia if element in set(mots)] # this is list comprehension, but it can be replaced by regular loop
print(result)
dia.extend(mots)
print(dia)
|