The set collection

This article is participating in Python Theme Month,See the activity link for details

The set set is a very useful data structure. A set is similar to a list except that it cannot contain duplicate values. It’s really useful in a lot of situations. For example, you might want to check if there are duplicates in the list. You have two choices. The first involves using a for loop. Something like this:

Set: no repetition of elements is allowed, and intersection and union operations are performed

Represents the relationship between {} and dict: The set stores only keys

Essence: An unordered collection of non-repeating elements

list1 = ['a'.'b'.'c'.'b'.'d'.'m'.'n'.'n']

duplicates = []
for value in list1:
    if list1.count(value) > 1:
        if value not in duplicates:
            duplicates.append(value)

print(duplicates)
>>> ['b'.'n']
Copy the code

But there is a simpler, more elegant solution that involves sets. You can simply do something like this:

list1 = ['a'.'b'.'c'.'b'.'d'.'m'.'n'.'n']
duplicates = set([x for x in list1 if some_list.count(x) > 1])  # set(list1)
print(duplicates)
>>> set(['b'.'n'])
Copy the code

Sets also have a few other methods. Here are some of them.

increase

  • The add () to add

    • A single element. If the added element exists, adding fails. No error is reported
    • Multiple elements, added with add in a set, can only be added to tuples, not lists and dict
  • Update the update ()

    • Cannot be added directly. Arguments can be lists, tuples, dictionaries, etc.
# add(66) set1.add(55) # Add (66) set1.add(55) Add ([77,88]) #TypeError: unhashable: 'list' s1.add((77, 88)) # s1.add({1:"a"}) # To add a set, you can only add tuples, not lists and dict # update(), Set2 = {11, 22, 33, 44, 55} # set2.update(66) # TypeError: 'int' object is not iterable set2.update([66]) # [] set2.update((77, 88)) # () set2.update({"12": 14, "13": Set2. update("hgjhgaa") # add characters to the list (not duplicate)Copy the code

delete

  • Remove () An error occurs if the removed element does not exist.
  • Discard () No error occurs if the deleted element does not exist.
  • Pop () randomly removes an element from the collection
  • Clear () clears the collection
set2.remove(77)
set2.discard(33)
set2.pop()
set2.clear()
Copy the code

Intersection and union

# intersection and set s1 = {3, 54, 4, 5, 7} s2 = {3, 54, 4, 8, 90} # intersection: & print bitwise and 】 【 (s1 and s2) # and sets: | bitwise or print 】 (s1 | s2)Copy the code

The interview questions

# master: remove the repeating element in the list of s2 = set ([46, 3, 5, 65, 7, 65, 7]) # [] s3 = set ((2, 43, 54, 5, 4, 5)) # () s4 = set ({10: "a", 20: "B "}) #Copy the code

\