Detailed explanation of tuples, dictionaries and sets in Python

1. Tuple

Although the function of the list is very powerful, the burden is also heavy, which affects the operating efficiency to a great extent. Sometimes we don't need so many functions and would like to have a lightweight list. Tuple is exactly such a type.

1. Create a tuple

Formally, all elements of a tuple are placed in a pair of parentheses, and the elements are separated by commas. If there is only one element in the tuple, a comma must be added at the end.

x=(1,2,3)   #直接把元组赋值给一个变量
print(type(x))  #使用type()函数查看变量类型

print(x[0])     #元组支持使用下标访问特定的位置元素

print(x[-1])    #最后一个元素,元素也支持双向索引
#x[1]=4
x=(3)           #int类型
print(x)
x=(3,)          #如果元组中只有一个元素,必须在后面多写一个逗号
print(x)
x=()            #空元组
x=tuple()       #空元组
print(tuple(range(5))) #将其他迭代对象转换为元组

<class 'tuple'>
1
3
3
(3,)
(0, 1, 2, 3, 4)

The return value of many built-in functions is also an iterable object containing several tuples, such as enumerate(), zip(), etc.

The enumerate() function returns an iterable object containing several subscripts and values.
The zip() function is used to recombine the elements in multiple lists into tuples and return a zip object containing these tuples.

x=list(enumerate(range(5)))
print(x)

y=list(zip(range(3),'abcdefg'))
print(y)

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
[(0, 'a'), (1, 'b'), (2, 'c')]

2. Similarities and differences between tuples and lists

  1. Both lists and tuples are ordered sequences and both support the use ofBidirectional index access to elements, as well as usingThe count() method counts the number of occurrences of a specified elementandThe index() method gets the index of the specified element, a large number of built-in functions such as len(), map(), filter() and operators such as +, += and in can also be used on lists and tuples
  2. Tuples are immutable sequences, you cannot directly modify the values ​​of elements in the tuple, nor can you add or delete elements to the tuple.
  3. tupleNo methods such as append(), extend() and insert() are provided, elements cannot be added to the tuple; similarly, the tuple does not have remove() and pop() methods, nor does it support the del operation on the tuple elements. Elements cannot be deleted from the tuple, but can only be deleted using the del command. The entire tuple.
  4. Tuples also support slicing operations, but the elements in the tuple can only be accessed through slicing, and slicing is not allowed to modify the values ​​of the elements in the tuple, nor is the use of slicing operations to add or delete elements to the tuple.

3. Generator derivation

Traverse using the generator object __next__() method or the built-in function next()

>>> g = ((i+2)**2 for i in range(10))  #创建生成器对象
>>> g
<generator object <genexpr> at 0x0000000003095200>
>>> tuple(g)                           #将生成器对象转换为元组
(4, 9, 16, 25, 36, 49, 64, 81, 100, 121)
>>> list(g)             #生成器对象已遍历结束,没有元素了
[] 
>>> g = ((i+2)**2 for i in range(10))  #重新创建生成器对象
>>> g.__next__()        #使用生成器对象的__next__()方法获取元素
4
>>> g.__next__()        #获取下一个元素
9
>>> next(g)             #使用函数next()获取生成器对象中的元素
16

2. Dictionary

A dictionary contains several == "key:value"An unordered variable sequence of elements. Each element in the dictionary contains two parts: "key" and "value" separated by colons, which represent a mapping or correspondence relationship, also called an associative array. When defining a dictionary,The "key" and "value" of each element are separated by colons, and different elements are separated by commas. All elements are placed in a pair of curly brackets "{}".
The "key" of an element in a dictionary can be
Any immutable data, such as integers, real numbers, complex numbers, strings, tuples, etc., can be hashed data ==, but you cannot use lists, sets, dictionaries, or other mutable types as the "keys" of the dictionary. in addition,The "keys" in the dictionary do not allow duplication, but the "values" can be repeated.

3.1. Dictionary creation and deletion

使用赋值运算符“=”将一个字典赋值给一个变量即可创建一个字典变量。
>>> aDict = {
    
    'server': 'db.diveintopython3.org', 'database': 'mysql'}

也可以使用内置类dict以不同形式创建字典。
>>> x = dict()                               #空字典
>>> type(x)                                  #查看对象类型
<class 'dict'>
>>> x = {
    
    }                                   #空字典
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))     #根据已有数据创建字典
>>> d = dict(name='Dong', age=39)            #以关键参数的形式创建字典
>>> aDict = dict.fromkeys(['name', 'age', 'sex'])
                             #以给定内容为“键”,创建“值”为空的字典
>>> aDict
{
    
    'age': None, 'name': None, 'sex': None}

3.2. Dictionary element access

Each element in the dictionary represents a mapping relationship or correspondence relationship. The corresponding "value" can be accessed according to the provided "key" as a subscript. If this "key" does not exist in the dictionary, an exception will be thrown.

>>> aDict = {
    
    'age': 39, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict['age']                     #指定的“键”存在,返回对应的“值”
39
>>> aDict['address']                 #指定的“键”不存在,抛出异常
KeyError: 'address'

The dictionary object provides a get() method to return the "value" corresponding to the specified "key", and allows a specific "value" to be returned when the specified key does not exist. For example:

>>> aDict.get('age')                    #如果字典中存在该“键”则返回对应的“值”
39
>>> aDict.get('address', 'Not Exists.') #指定的“键”不存在时返回指定的默认值
'Not Exists.'

Use the items() method of a dictionary object to return the dictionary's key and value pairs.
Use the keys() method of a dictionary object to return the keys of the dictionary.
Use the values() method of a dictionary object to return the values ​​of the dictionary.

Use a for loop to iterate directly over the elements in a generator object

>>> g = ((i+2)**2 for i in range(10))
>>> for item in g:                #使用循环直接遍历生成器对象中的元素
        print(item, end=' ')
4 9 16 25 36 49 64 81 100 121 

Case 1: First generate a string containing 1000 random characters, and then count the occurrences of each character

>>> import string
>>> import random
>>> x = string.ascii_letters + string.digits + string.punctuation
>>> y = [random.choice(x) for i in range(1000)]
>>> z = ''.join(y)
>>> d = dict()                  #使用字典保存每个字符出现次数
>>> for ch in z:
    d[ch] = d.get(ch, 0) + 1

3.3. Add, modify and delete dictionary elements

When assigning a value to a dictionary element with a specified "key" as a subscript, it has two meanings:
1) If the "key" exists, it means modifying the value corresponding to the "key";
2) If it does not exist, it means adding one A new "key:value" pair, that is, adding a new element.

>>> aDict = {
    
    'age': 35, 'name': 'Dong', 'sex': 'male'}
>>> aDict['age'] = 39                  #修改元素值
>>> aDict
{
    
    'age': 39, 'name': 'Dong', 'sex': 'male'}
>>> aDict['address'] = 'SDIBT'         #添加新元素
>>> aDict
{
    
    'age': 39, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}

Using the update() method of the dictionary object, you can add the "key:value" of another dictionary to the current dictionary object all at once. If the same "key" exists in the two dictionaries, the "value" in the other dictionary will be added. Update the current dictionary accordingly.

>>> aDict = {
    
    'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.update({
    
    'a':97, 'age':39})  #修改’age’键的值,同时添加新元素’a’:97
>>> aDict
{
    
    'score': [98, 97], 'sex': 'male', 'a': 97, 'age': 39, 'name': 'Dong'}

If you need to delete specified elements in the dictionary, you can use the del command.

>>> del aDict['age']               #删除字典元素
>>> aDict
{
    
    'score': [98, 97], 'sex': 'male', 'a': 97, 'name': 'Dong'}
也可以使用字典对象的pop()和popitem()方法弹出并删除指定的元素,例如:
>>> aDict = {
    
    'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.popitem()                #弹出一个元素,对空字典会抛出异常
('age', 37)
>>> aDict.pop('sex')               #弹出指定键对应的元素
'male'
>>> aDict
{
    
    'score': [98, 97], 'name': 'Dong'}

3. Collection

Sets belong to Pythonunordered variable sequence, use a pair of braces as delimiters, use commas to separate elements, and each element in the same collection is unique.Duplication between elements is not allowed

Collections can only contain immutable (or hashable) data such as numbers, strings, and tuples, but not mutable types such as lists, dictionaries, and sets.

3.1. Creation and deletion of collection objects

A collection object can be created by directly assigning the collection to a variable.

>>> a = {
    
    3, 5}                         #创建集合对象
>>> type(a)                            #查看对象类型
<class 'set'>

You can also use the set() function to convert other iterable objects such as lists, tuples, strings, and range objects into sets. If there are duplicate elements in the original data, only one will be retained when converting to a set; if the original data There are unhashable values ​​in the sequence or iteration object and cannot be converted into a set, and an exception is thrown.

>>> a_set = set(range(8, 14))                     #把range对象转换为集合
>>> a_set
{
    
    8, 9, 10, 11, 12, 13}
>>> b_set = set([0, 1, 2, 3, 0, 1, 2, 3, 7, 8])   #转换时自动去掉重复元素
>>> b_set
{
    
    0, 1, 2, 3, 7, 8}
>>> x = set()                                     #空集合

1) Adding and deleting collection elements.
Use the add() method of the collection object to add new elements. If the element already exists, the operation will be ignored and no exception will be thrown. The update() method is used to merge elements from another collection into in the current collection and automatically remove duplicate elements. For example:

>>> s = {
    
    1, 2, 3}
>>> s.add(3)                          #添加元素,重复元素自动忽略
>>> s
{
    
    1, 2, 3}
>>> s.update({
    
    3,4})                   #更新当前字典,自动忽略重复的元素
>>> s
{
    
    1, 2, 3, 4}

The pop() method is used to randomly delete and return an element in the collection, and throws an exception if the collection is empty; the
remove() method is used to delete elements in the collection, and throws an exception if the specified element does not exist;
discard() Used to delete a specific element from the collection. If the element is not in the collection, the operation is ignored;
the clear() method clears the collection and deletes all elements.

>>> s.discard(5)                     #删除元素,不存在则忽略该操作
>>> s
{
    
    1, 2, 3, 4}
>>> s.remove(5)                      #删除元素,不存在就抛出异常
KeyError: 5
>>> s.pop()                          #删除并返回一个元素
1

2) Set operations


>>> a_set = set([8, 9, 10, 11, 12, 13])
>>> b_set = {
    
    0, 1, 2, 3, 7, 8}
>>> a_set | b_set                     #并集
{
    
    0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set.union(b_set)                #并集
{
    
    0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13}
>>> a_set & b_set                     #交集
{
    
    8}
>>> a_set.intersection(b_set)         #交集
{
    
    8}
>>> a_set.difference(b_set)           #差集
{
    
    9, 10, 11, 12, 13}
>>> a_set - b_set
{
    
    9, 10, 11, 12, 13}
>>> a_set.symmetric_difference(b_set) #对称差集
{
    
    0, 1, 2, 3, 7, 9, 10, 11, 12, 13}
>>> a_set ^ b_set
{
    
    0, 1, 2, 3, 7, 9, 10, 11, 12, 13}

Guess you like

Origin blog.csdn.net/qq_52108058/article/details/133753729