set

Ekkart Kleinod  • 
  • Sets erzeugen: {1, 2}
    • außer leeres Set: set()
    • nicht verwenden: {}, das ist ein leeres dict

Duplikate aus Listen entfernen

Sets haben unique Objekte, folgender Code ist gute Praxis:

l = ['spam', 'spam', 'spam', 'eggs', 'spam', 'eggs', 'bacon', 'eggs']
print(set(l))
print(list(set(l)))
{'eggs', 'spam', 'bacon'}
['eggs', 'spam', 'bacon']

Mengenoperationen

Sind verfügbar, siehe https://realpython.com/python-sets/

  • x1.union(x2) = x1 | x2
    • all elements in either x1 or x2
  • x1.intersection(x2) = x1 & x2
    • all elements common to both x1 and x2
  • x1.difference(x2) = x1 - x2
    • all elements that are in x1 but not in x2
  • x1.symmetric_difference(x2) = x1 ^ x2
    • all elements in either x1 or x2, but not both
  • x1.isdisjoint(x2)
    • Determines whether or not two sets have any elements in common.
  • x1.issubset(x2) = x1 <= x2
    • every element of x1 is in x2
  • x1 < x2
    • every element of x1 is in x2, and x1 and x2 are not equal
  • x1.issuperset(x2) = x1 >= x2
    • x1 contains every element of x2
  • x1 > x2
    • x1 contains every element of x2, and x1 and x2 are not equal