Python set set type operation summary

  • 2020-04-02 14:19:36
  • OfStack

In addition to dictionaries, lists, and tuples, there is a very useful data structure in Python, which is set. If you use set flexibly, you can subtract a lot of operations (although set can be replaced by lists).

Small example

1. If I want to find the same item in many lists, it is best to use sets


x & y & z # intersection

2. To weight


>>> lst = [1,2,3,4,1]
>>> print list(set(lst))
[1, 2, 3, 4]

usage

Notice that set doesn't have the concept of position so the list method doesn't slice anything, it's converted to list when it's needed, okay

The built-in function creates a set


set([1, 2, 3, 4])

Basic operation


t.add('x')            # To add a
s.update([10,37,42])  # in s Add multiple items in t.remove('H') # To delete a len(s)  # set The length of the x in s # test x Whether it is s A member of the   x not in s   # test x If not s A member of the   s.issubset(t) 
s <= t  # To test whether s Each of the elements in t In the   s.issuperset(t) 
s >= t  # To test whether t Each of the elements in s In the   s.union(t) 
s | t  # Return a new set contains s and t Each of the elements   s.intersection(t) 
s & t  # Return a new set contains s and t Public elements in   s.difference(t) 
s - t  # Return a new set contains s There is however, t Elements that are not in   s.symmetric_difference(t) 
s ^ t  # Return a new set contains s and t The element that does not repeat   s.copy()  # return set " s A shallow copy of  


Related articles: