[Python study notes] dict and set

dict and set


dict

dictThe full name dictionary is also a dictionary

>>> sx = {'沙县拌面': 7, '蒸饺': 6, '鸭腿套餐': 12}
>>> sx['沙县拌面']
7

key-value storage

keyIf there is no error, it will be reported, how to avoid:

  1. >>> '糖醋排骨' in sx # 用in来判断key是否存在
    False
    
  2. >>> sx.get('Thomas') #使用get()方法,key不存在的话,会返回None
    >>> sx.get('Thomas', -1) #或者自己指定value
    -1
    

    ps. When returning None, the result is not displayed.

pop( )

Use pop () method to delete one key, the corresponding one valuewill also be deleted

>>> d.pop('蒸饺')
6
>>> d
{'沙县拌面': 7, '鸭腿套餐': 12}

The order in which the dict is stored has nothing to do with the order in which the keys are placed.

Space for time

dict compared to list:

dict:

  1. The search and insert speed is extremely fast, and will not slow down as the key increases;
  2. It takes a lot of memory and wastes a lot of memory.

list:

  1. The time to find and insert increases with the increase of elements;
  2. It takes up less space and wastes less memory.

dictThe keymust be immutable objects


set

setAnd dictsimilar, but also a set keyof collection, but not stored value.

Because it keycan't be repeated, there setis no repeat in the middle key.

Create set

>>> s = set([1, 2, 3])
>>> s
{1, 2, 3}

Automatically filter duplicate elements

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}

Add element add (key)

>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}  #重复添加,并不会有效果

Remove element remove (key)

>>> s.remove(4)
>>> s
{1, 2, 3}

Set can be regarded as a collection in the mathematical sense (unordered, no repeating elements), so the two sets can do intersection and union operation:

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

Immutable object and mutable object understanding:

variable:

>>> a = ['c', 'b', 'a']
>>> a.sort() #对a进行排序
>>> a
['a', 'b', 'c']

Immutable:

>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a #a并没有被改变
'abc'
Published 18 original articles · Likes6 · Visits 1859

Guess you like

Origin blog.csdn.net/qq_43479203/article/details/105499453