Python set

Posted by neerav on Sat, 25 Dec 2021 13:43:26 +0100

 

 

Features of the collection:

1. There are no duplicate elements, and the elements are stored in disorder (so the set has no subscripts and slices)

2. When used, {} is distinguished from Dictionary: when the element in curly braces is not a key value pair, it is a collection

3. The bottom layer of the collection is actually encapsulated through a dictionary

Simple use of collections:

Define an empty collection

set1 = set()
print(type(set1), len(set1))

output

<class 'set'> 0

Add operation

Add is used to add elements

update is used to merge collections

Due to the disorder of the set, after merging the set, it is not output in the order of splicing.

set1 = set()
set1.add('Military moves the universe')
set2 = {'jsy', 'fragrance of rice', 'The price of love', 'Large bowl wide noodles'}
set2.update(set1)
print(set2)

The output result is not unique. Each output may have a new order.

{'fragrance of rice', 'Large bowl wide noodles', 'Military moves the universe', 'jsy', 'The price of love'}

Remove operation

remove: when removing an element that is not in a collection, an error is reported

discard: no error will be reported when removing elements that are not in a collection

del , can only be used for the set itself, not for elements, because elements in the set are chaotic and have no subscripts

clear , empty the collection, leaving an empty collection

pop # randomly delete an element in the set

Intersection union difference set operation

intersection

union

difference set

Take the following examples:

set2 = {1, 2, 3, 4, 5}
set3 = {3, 4, 5, 6, 7, 8, 9}

result = set2.intersection(set3)
print(result)

result = set2.union(set3)
print(result)

result = set2.difference(set3)  #The result is the different part between set2 and set3, with set2 as the main body
print(result)

Output:

{3, 4, 5}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2}

Operators can be used to represent intersection, union and difference sets

Intersection&

Union|

Difference set-

set2 = {1, 2, 3, 4, 5}
set3 = {3, 4, 5, 6, 7, 8, 9}

print(set2 & set3)  # Intersection symbol&
print(set2 | set3)  # Union symbol|
print(set2 - set3)  # Difference set symbol-

Output:

{3, 4, 5}
{1, 2, 3, 4, 5, 6, 7, 8, 9}
{1, 2}

List, tuple, dictionary, set, big summary:

list: allow repetition, order, subscript and slicing

tuple: duplicate is allowed. The elements inside cannot be added, deleted or modified, but can only be viewed

dict: Elements in the dictionary exist in the form of key value pairs. Key: uniqueness. Value: can be repeated

set: elements are not allowed to be repeated and are out of order

Type conversion between them:

List ----- > tuple, set (when converting a list to a set, be careful not to have duplicate elements, otherwise the length will change)

tuple----->list,set

Set ----- > list, tuple

Special treatment is required when the dictionary is involved in the conversion of

Dict - > list, tuple (only the keys of the dictionary can be converted, not the values)

List ----- > dict (it can be transferred when the following conditions occur)

The list must be a} list or a tuple, and there are only two elements:

list = [['a', {1}], ('', 2), ('c', 3)]
print(dict(list))

Output:

{'a': {1}, '': 2, 'c': 3}

Differences between set and list methods:

Because of the disorder of the set and no subscript, it is different from the list in method.

Append (add element) extend (realize splicing of list) insert (insert element in a subscript) ---- > List

Add (add element) update (merge of two sets) -- > Set

About instances of collections:

*Generate a 4-digit verification code composed of 5 groups (no repetition), letters and numbers

1. Use random Choice() randomly selects a character in the string

2. The subscript of the character in the string can also be randomly obtained for assignment

import random

m = 'asdfghjklqwertyuiopzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789'
set5 = set()
while True:
    s = ''
    for i in range(4):
        ran = random.choice(m)  # Random selection of verification code with choice
        s += ran
        # index = random.randint(0,len(m)-1)
        # s += m[index]
    set5.add(s)
    if len(set5) == 5:
        break
print(set5)

Output not unique

{'HINS', 'i71y', 'CU1i', 'Rcbx', 'XBeX'}

Topics: Python Pycharm