From entry to prison-tuples and dictionaries

Getting started N day

Tuple

Tuple data type is a container, the () as a marker container,
immutable (no add, delete, change)
inside a plurality of spaced elements :( element 1, element 2, element 3 by commas ...)
element can Is any type of data and can be repeated

t1 = (10, 11, 12, '123', 'abc')
print(type(t1), t1)

A tuple with only one element (element,)
If there is one and only one element in a tuple, then the only element must be followed by a comma

t2 = (1)
t3 = (1,)
print(t2, type(t2))  # 1 <class 'int'> 不是元组类型
print(t3, type(t3))  # (1,) <class 'tuple'> 元组类型

Empty tuple

t4 = ()
print(t4, type(t4))  # () <class 'tuple'>

Omit the brackets.
If there is no ambiguity, you can omit the () of the tuple, and directly separate multiple elements with a comma to represent a tuple

t5 = 1, 3, 5, 1, 5
print(t5, type(t5))  # (1, 3, 5, 1, 5) <class 'tuple'>

# 获取元素:列表获取元素的方法元组都支持
#例如遍历和切片:
```python
t6 = (1, 3, 5, 4)
for i in t6:
    print(i)
print(t6[-1], t6[2])
print(t6[:])

Keep the number of variables consistent with the number of elements in the tuple to obtain the values ​​of all the elements in the tuple.
Variable 1, Variable 2, Variable 3...=Tuple

t7 = (1, 2, 3, 4, 5, 6)
a, b, c, d, e, f = t7
print(a, b, c, d, e, f)  # 1 2 3 4 5 6

'''
a, b, c, d=t7
print(a, b, c, d)   #ValueError: too many values to unpack (expected 4)
a, b, c, d, e, f,g = t7
print(a, b, c, d, e, f,g)   # ValueError: not enough values
                               to unpack (expected 7, got 6)

When multiple variables are used to obtain tuple elements at the same time, the number of variables can be less than the number of elements in the tuple,
but there must be only one variable before *

nums = (1, 3, 5, 7, 6, 5)
a, b, c, *d = nums
print(a, b, c, *d)  # 1 3 5 7 6 5
print(*d)  # 7 6 5

*a, b, c = nums
print(*a)  # 1 3 5 7
print(b)  # 6
print(c)  # 5

a, *b, c = nums
print(a)  # 1
print(*b)  # 3 5 7 6
print(c)  # 5

'''
# 多个变量前面有*会报错
*a,*b,c,d=nums
print(*a,*b,c,d) # TypeError: print() argument after * must 
                    be an iterable, not int

After sorting the tuples, a new list is generated

nums2 = (1, 3, 5, 7, 1, 3, 5)
new_nums2 = sorted(nums2)
print(new_nums2)  # [1, 1, 3, 3, 5, 5, 7]

list1=[1, 1, 3, 3, 5, 5, 7]
print(tuple(list1)) # (1, 1, 3, 3, 5, 5, 7)
print(tuple('abc'))  # ('a', 'b', 'c')
print(tuple(range(1, 5)))  # (1, 2, 3, 4)

Dictionary
'''
Function: Use a dictionary to store multiple data with different meanings.
Dictionary is a container data type. {} is used as the symbol of the container, and multiple elements are separated by commas (elements must be key-value pairs)
{ Key 1: value 1, key 2: value 2,...}
Features: variable, support for addition, deletion, modification and search (subscript operations are not supported), the
dictionary is disordered
Element: must be a key-value pair
key: must be immutable The data (numbers, strings, tuples) generally use strings,
keys are used to distinguish and describe, the only
value: no requirement

stu = {
    
    "姓名": "小明", '成绩': 15, '性别': '男', '年龄': 15}
print(stu['成绩'])  # 15
print(stu)

Empty dictionary

d1 = {
    
    }
print(type(d1))  # <class 'dict'>

Keys are immutable

d1 = {
    
    10: 10, 'x': 11, (1, 2): 15}
print(d1)
 d1 = {
    
    10: 10, 'x': 11, [1, 2]: 15}   TypeError: unhashable type: 'list'

Key is unique

d1 = {
    
    10: 10, 'x': 11, (1, 2): 15, 10: 1}
print(d1)  # 出现多个相同的键,打印结果只会显示其中一个 {10: 1, 'x': 11, (1, 2): 15}

Judging whether it is in order

print({
    
    10: 10, 'x': 11} == {
    
    'x': 11, 10: 10})  # 字典 True 无序的
print([10, 'x', 11] == ['x', 11, 10])  # 列表为False有序的

Dictionary CRUD
'' '
check: to get a single value of
the dictionary [key] Gets a value corresponding to the specified key value obtained will be given if the absence
dictionary .get (key) Gets the value corresponding to the specified key value does not exist if the acquired It will return None
dictionary.get(key,value) Get the value corresponding to the specified key, if the obtained value does not exist, it will return value

dog = {
    
    'name': '旺财', 'age': '2', 'sex': '母狗', 'breed': '土狗'}

print(dog['age'], dog['name'])  # 2 旺财
print(dog.get('age'))  # 2
print(dog.get('weight'))  # None
print(dog.get('weight', 'gong'))  # gong

Iterating over key-value pairs left the dictionary invalid


dog = {
    
    'name': '旺财', 'age': '2', 'sex': '母', 'breed': '土狗'}
for i in dog:
    print(i)  # 'name' 'age' 'sex' 'breed'
    print(dog[i])  # 旺财 2 母 土狗

Add and change
``'
Dictionary [key]= value when the key exists is to modify the value corresponding to the specified key: when the key does not exist, it is to add a key-value pair
'''

dog = {
    
    'name': '旺财', 'age': '2', 'sex': '母', 'breed': '土狗'}
dog['name'] = '小黑'  # 修改‘name’的值
dog['weight'] = '12'  # 增加‘weight’:‘12’
print(dog)  # {'name': '小黑', 'age': '2', 'sex': '母',
#                'breed': '土狗', 'weight': '12'}

delete

'''
del dictionary [key] delete the key-value pair corresponding to the specified key
dictionary.pop(key) take out the value corresponding to the specified key
'''

dog = {
    
    'name': '旺财', 'age': '2', 'sex': '母', 'breed': '土狗'}
del dog['breed']
del_name = dog.pop('name')
print(dog)  # {'age': '2', 'sex': '母'}
print(del_name)  # 旺财

Define a variable to save the information of a class, the class information mainly includes: class teacher, lecturer, class name,
location, capacity, all students

class_python = {
    
    
    'class_name': "python_2004", '位置': "肖家河", "容量": '42',
    '班主任': {
    
    "姓名": '张老师', '性别': '女', 'age': '18', '电话': '123456',
            'qq': '123456'},
    '讲师': {
    
    "姓名": '余老师', '性别': '女', 'age': '18', '电话': '123456',
           'qq': '123456', '级别': 'x'},
    '学生':
        {
    
    '学生1': {
    
    '性别': '男', '年龄': 24, "学历": '大专', "专业": '计算机',
                 '电话': '123456'},
         '学生2': {
    
    '性别': '男', '年龄': 23, "学历": '大专', "专业": '计算机',
                 '电话': '123456'},
         '学生3': {
    
    '性别': '男', '年龄': 24, "学历": '大专', "专业": '计算机',
                 '电话': '123456'},
         '学生4': {
    
    '性别': '男', '年龄': 21, "学历": '大专', "专业": '计算机',
                 '电话': '123456'},
         '学生5': {
    
    '性别': '男', '年龄': 20, "学历": '大专', "专业": '计算机',
                 '电话': '123456'}}
}
print(class_python)

# 获取班主任的名字
t_name = class_python['班主任']["姓名"]
print(t_name)

The dictionary does not support addition and multiplication operations, nor does it support comparison of sizes
'''
in and not in determine whether the specified key exists
in the dictionary key in The dictionary determines whether the specified key exists in the dictionary
'''

d1 = {
    
    'a': 10, 'b': 12, 'c': 30}
print(10 in d1)  # False
print('a' in d1)  # True

# 相关函数:len

print(len(d1))  # 获取长度 3

Dictionary type conversion

dict (data): Convert the specified data into a dictionary.
Requirement: The
data itself is a sequence, and the elements in the sequence must be a small sequence of length 2.
The first element in the small sequence is immutable data

list (dictionary) converts the specified dictionary into a list (using the key of the dictionary as the element of the list)

list1 = [(1, 2), [3, 4], 'ab']
print(dict(list1))  # {1: 2, 3: 4, 'a': 'b'}

dict1 = {
    
    1: 1, 2: 3, 4: 5}
print(list(dict1))  # [1, 2, 4]

Related method
'''
Dictionary.clear()
'''

d1 = {
    
    'a': 10, 'b': 20, 'c': 30}
d1.clear()
print(d1)  # {} 清空

Assigning an empty dictionary is very inefficient and not recommended

d2 = {
    
    'a': 10, 'b': 20, 'c': 30}
d2 = {
    
    }
print(d2)  # {}

Dictionary.copy() Copy the dictionary to generate a new dictionary exactly the same and return

d1 = {
    
    'a': 10, 'b': 20, 'c': 30}
d2 = d1
print(d2)  # {'a': 10, 'b': 20, 'c': 30},将d1赋值给d2,如果修改d2,会影响d1
print(id(d1), id(d2))  # 4728616 4728616 地址相同

d3 = d1.copy()
print(d3)  # {'a': 10, 'b': 20, 'c': 30} 复制一个d3,修改d3不会影响d1
print(id(d1), id(d3))  # 5777192 5778232 地址不同

dict.fromkeys(sequence) creates a new dictionary, the key is each element in the sequence, and the value is None

print(dict.fromkeys('addada'))  # {'a': None, 'd': None}

Remove duplicate elements

nums = [1, 1, 1, 2, 3, 5, 5, 5, 3]

nums2 =list(dict.fromkeys(nums))
print(nums2)          # [1, 2, 3,  5 ]
print(dict.fromkeys('ab', 1))  # {'a': 1, 'b': 1}
print(dict.fromkeys('ab', [1, 2, 2]))  # {'a': [1, 2, 2], 'b': [1, 2, 2]

Dictionary.keys() Get all the keys of the dictionary (the return value is a sequence, but not a list)
Dictionary.values() Get all the values ​​of the dictionary (the return value is a sequence, but not a list)

d1={
    
    'a': 1, 'b': 1}
print(d1.keys())   # dict_keys(['a', 'b'])
print(d1.values()) # dict_values([1, 1])
print(d1.items()) # dict_items([('a', 1), ('b', 1)])

Dictionary.setdefault(key, value) Add key-value pairs to the dictionary (only add but not modify)

d1={
    
    'a': 1, 'b': 1}
d1.setdefault('c',1)
print(d1)  # {'a': 1, 'b': 1, 'c': 1}

d1.setdefault('c',3)
print(d1)  # {'a': 1, 'b': 1, 'c': 1}

Dictionary 1.update (Dictionary 2) Add all key-value pairs in
dictionary 2 to dictionary 1. Dictionary 2 is not necessarily a dictionary, but can also be a sequence that can be converted into a dictionary

d1={
    
    'a': 1, 'b': 1}
d2={
    
    'c': 1, 'd': 1}
d1.update(d2)
print(d1)   # {'a': 1, 'b': 1, 'c': 1, 'd': 1}

Guess you like

Origin blog.csdn.net/weixin_44628421/article/details/108856341