Python study notes | 1 Data container

Python | 1 data container

Contents of this chapter: Data containers in Python, such as list, tuple, str, set, dict, etc.

All relevant codes can be viewed at https://github.com/hzyao/Python-Cookbook .
It’s wonderful to learn and practice at the same time, and to discover in time! It may taste better if eaten together!

By the way, how many people like me miss R when they open Python?

data container

1 What is a data container

Data container: A data type that can store multiple elements. The elements can be data of any type, such as strings, numbers, Boolean, etc.

Data container types: list (list), tuple (tuple), str (string), set (set), dict (dictionary). They each have their own characteristics, but they all meet the characteristics of being able to accommodate multiple elements.

2 list

Each data in the list is called an element.

  • as []an identifier
  • ,Separate each element in the list with
  • Lists can store multiple data at one time, and can be of different data types, and support nesting.
# 定义列表字面量
["yhz", "lr", "xmy", 666, True]

# 定义列表变量
my_list = ["yhz", "lr", "xmy", 666, True]
print(my_list)
print(type(my_list))

# 定义空列表
o_list = []
o_list = list()
print(o_list)
print(type(o_list))

# 定义一个嵌套的列表
my_list = [[1,2,3], [4,5,6]]
print(my_list)
print(type(my_list))

2.1 Subscript index of list

Each element of the list has a number, which we call a subscript index. 列表[下标]It can be taken out. Nested lists also support subscript indexing.

From front to back, starting from 0, increasing in sequence, 0,1,2,3...;

From back to front, starting from -1, decreasing in order, -1,-2,-3...

# 列表的下标索引
my_list = ["yhz", "lr", "xmy", 666, True]
print(my_list[0])
print(my_list[1])
print(my_list[4])

# 倒序取出
print(my_list[-5])
print(my_list[-4])
print(my_list[-1])

# 取出嵌套列表元素
my_list = [[1,2,3], [4,5,6]]
print(my_list[0][1])

Note: Pay attention to the value range of the subscript index. Elements cannot be retrieved beyond the range. Remember to start from 0.

2.2 Common operations on lists

Supplementary knowledge

Function vs. Method

A function is an encapsulated unit of code that provides specific functionality.

In Python, if a function is defined as a member of a class, the function is called a method .

# 函数
def add(x, y):
		return x + y

# 方法
class Student:
		def add(self, x, y):
				return x + y

Methods have the same functions as functions, they have incoming parameters and return values, but the method usage format is different.

# 函数的使用
num = add(1, 2)

# 方法的使用
student = Student()
num = student.add(1, 2)
  • Query function

    Function: Find the subscript of a specified element in the list, and report an error if it cannot be found ValueError.

    grammar:列表.index(元素)

    indexIt is the built-in method (function) of the list object (variable).

  • Modify function

    Function: Modify the element value at a specific position (index), and reassign the value of the specified subscript.

    grammar:列表[下标] = 值

  • Insert function

    Function: Insert the specified element at the specified subscript position.

    grammar:列表.insert(下标, 元素)

  • append element

    Function: Append the specified element to the end of the list.

    Syntax: 列表.append(元素)(Append one), 列表.extend(其他数据容器)(Take out the contents of other data containers and append them to the end of the list in turn)

  • Delete element

    Syntax: del 列表[下标], 列表.pop(下标)(remove elements from the list), 列表.remove(元素)(remove the first occurrence of an element in the list)

  • clear the list

    grammar:列表.clear()

  • Count the number of elements in a list

    grammar:列表.count(元素)

# 列表常用操作
## 查询元素下标
my_list = ["yhz", "lr", "xmy", 666, True]
my_list.index("lr")

## 修改元素
my_list[2] = "xiaomanyao"
print(my_list)

## 插入元素
my_list.insert(1, "loves")
print(my_list)

## 追加元素
my_list.append("耶")
print(my_list)

## 追加一批元素
add_list = [1,2,3]
my_list.extend(add_list)
print(my_list)

## 删除元素
del my_list[9]
print(my_list)

## 从列表中取出元素并将其删除
delete = my_list.pop(8)
print(my_list)
print(delete)

## 删除某元素在列表中的第一个匹配项
my_list.remove(1) # 豁,1 就是 True 哈!帅的!
print(my_list)

## 清空列表
my_list.clear()
print(my_list)

## 统计某元素在列表中的数量
my_list = ["yhz", "lr", "xmy", 666, True, "lr"]
count = my_list.count("lr")
print(count)

## 统计列表中全部元素数量
count = len(my_list)
print(count)

Summary:
列表.append(元素): Append an element to the list;
列表.extend(容器): Take out the contents of the data container one by one and append to the end of the list;
列表.insert(下标,元素): Insert the specified element at the specified subscript; : Delete the
del 列表[下标]specified subscript element from the list;
列表.pop(下标): Delete the specified subscript from the list Element;
列表.remove(元素): Delete the first matching item of this element from front to back;
列表.clear(): Clear the list;
列表.count(元素): Count the number of times this element appears in the list; :
列表.index(元素)Search for the specified element and report an error ValueError if it cannot be found at the subscript of the list;
len(列表): Count within the container How many elements are there.

List features:

  1. Can accommodate multiple elements (upper limit is 2**63-1)
  2. Can accommodate different types of elements (mixed)
  3. Data is stored in order (with subscripted serial numbers)
  4. Allow duplicate data to exist
  5. Elements can be modified (added or deleted)

2.3 Loop traversal of lists

Traversal: Taking out and processing the elements in the container one by one is called a traversal operation. You can use while or for loops.

Comparison of while loop and for loop

On loop control:

  1. The while loop can customize the loop conditions and control it by itself
  2. The for loop cannot customize the loop conditions. It can only retrieve data from the container one by one.

On an infinite loop:

  1. The while loop can loop infinitely through conditional control
  2. The for loop is theoretically not possible because the capacity of the container being traversed is not infinite.

In usage scenarios:

  1. The while loop is suitable for any scenario where you want to loop
  2. The for loop is suitable for traversing data containers or simple fixed-number loop scenarios.
# while 循环遍历列表
my_list = ["yhz", "lr", "xmy", 666, True, "lr"]

def list_while(data):
    index = 0
    while index < len(data):
        element = data[index]
        print(element)
        index += 1

list_while(my_list)
# for 循环遍历列表
my_list = ["yhz", "lr", "xmy", 666, True, "lr"]

def list_for(data):
    for element in my_list:
        print(element)

list_for(my_list)
# 练习:遍历取偶数
list = [1,2,3,4,5,6,7,8,9,10]
new_list = []
i = 0
while i < len(list):
    if list[i] % 2 == 0:
        new_list.append(list[i])
    i += 1
print(new_list)

for i in list:
    if i % 2 == 0:
        new_list.append(i)
print(new_list)

3-tuple

Tuples, like lists, can encapsulate multiple elements of different types. The biggest difference is that once a tuple is defined, it cannot be modified (if a list is nested in a tuple, the elements in the list can be modified).

Tuples are ()defined and ,separated by separate data. The data can be of different data types. It also supports nesting and subscript indexing. The writing method is the same.

Note: A tuple has only one data, and a comma must be added after this data , otherwise it is not a tuple type.

# 定义元组字面量
("yhz", "lr", "xmy", 666, True)

# 定义元组变量
my_tuple = ("yhz", "lr", "xmy", 666, True)
print(my_tuple)
print(type(my_tuple))

# 定义空元组
o_tuple = ()
o_tuple = tuple()
print(o_tuple)
print(type(o_tuple))

# 定义单个元素的元组,切记后面加逗号
single_tuple = ("hello",)
type(single_tuple)

3.1 Common operations on tuples

index(): Search for a certain data, and return the corresponding subscript if the data exists, otherwise an error will be reported;
count(): Count the number of times a certain data appears in the current tuple;
len(元组): Count the number of elements in the tuple.

# 元组的常用操作
my_tuple = ("yhz", "lr", "xmy", 666, True, "lr")

## 查找元素对应下标
my_tuple.index(666)

## 统计元素在当前元组中出现的次数
my_tuple.count("lr")

## 统计当前元组内元素个数
len(my_tuple)

3.2 Loop traversal of tuples

# 元组的遍历
my_tuple = ("yhz", "lr", "xmy", 666, True, "lr")

index = 0
while index < len(my_tuple):
        element = my_tuple[index]
        print(element)
        index += 1

for element in my_tuple:
        print(element)
# 元组中嵌套列表,列表中元素可修改
my_tuple = (["yhz", "lr", "xmy"], 666, True, "lr")
my_tuple[0][2] = "xiaomanyao"
my_tuple

4 string

We are already familiar with strings! a brief introdction!

A string is a container of characters. A string can store any number of characters. It can only store strings . It can be indexed using subscripts and can also be traversed.

Like a tuple, it is a data container that cannot be modified . Operations such as modifying, removing, and appending specified characters cannot be completed. If such operations are necessary, only a new string will be obtained, and the old string cannot be modified.

4.1 Common operations on strings

  • Finds the starting subscript index value of a specific string.字符串.index(字符串)
  • 字符串1Replace, replace everything in the string 字符串2。with Note: It does not modify the string itself, but gets a new string.字符串.replace(字符串1, 字符串2)
  • Split, divide the string into multiple strings according to the specified string delimiter, and store them in a list object. Note: The string itself does not change, but a list object is obtained.字符串.split(字符串分隔符)
  • Regularization operation, 字符串.strip()remove leading and trailing spaces, 字符串.strip(字符串)remove leading and trailing specified strings.
  • 字符串.count(某字符串)Count the number of occurrences of a certain string in a string and len(字符串)count the length of the string.
# 通过下标索引取值
my_str = "xiao man yao"
value1 = my_str[3]
value2 = my_str[-1]
print(value1, value2)

# 获取元素起始下标
index = my_str.index("man")
print(index)

# 替换
new_my_str = my_str.replace("yao", "liu")
print(new_my_str)

# 分割
my_str_list = my_str.split(" ")
print(my_str_list)
print(type(my_str_list))
# 规整操作
## 去除前后空格
my_str = "  xiao man yao        "
new_my_str = my_str.strip()
print(new_my_str)

## 去除前后指定字符串
my_str = "axiao man yao"
new_my_str = my_str.strip("ao")
print(new_my_str)
# 统计某字符串在字符串中的出现次数
my_str = "xiao man yao"
count = my_str.count("ao")
print(count)

lenth = len(my_str)
print(lenth)

Summary:
字符串[下标]:Retrieve characters at specific positions based on subscript index;
字符串.index(字符串):Find the subscript of the first match of a given character;
字符串.replace(字符串1, 字符串2):Replace all string 1 in the string with string 2; the original string will not be modified , but get a new one;
字符串.split(字符串): According to the given string, separating the string will not modify the original string, but get a new list; :
字符串.strip() / 字符串.strip(字符串)Remove the leading and trailing spaces and newlines or specify the string;
字符串.count(字符串): Count the number of occurrences of a certain string in a string;
len(字符串): Count the number of characters in a string.

5 sequences

Sequence: A type of data container whose content is continuous and ordered and can be indexed using subscripts. Lists, tuples, and strings can all be considered sequences.

5.1 Slicing of sequences

Sequences support slicing, that is, lists, tuples, and strings, all support slicing operations.

Slicing: Remove a subsequence from a sequence.

Syntax: 序列[起始下标:结束下标:步长]
It means to remove elements from the sequence starting from the specified position and ending at the specified position to get a new sequence:

  • The starting subscript indicates where to start. It can be left blank. If left blank, it is regarded as starting from the beginning;
  • The end subscript (not included) indicates where it ends. It can be left blank. If left blank, it is regarded as intercepted to the end;
  • The step size indicates that the interval between elements is taken in sequence.
    • Step size 1 means taking elements one by one (the default step size is 1 and can be omitted)
    • Step size 2 means that each time one element is skipped and taken
    • The step size N means that N-1 elements are skipped each time to take
    • If the step length is a negative number, it is taken in reverse direction (note that the starting subscript and ending subscript must also be marked in reverse)

Note: This operation will not affect the sequence itself, but will result in a new sequence.

# 切片
my_list = [0, 1, 2, 3, 4, 5, 6]
result = my_list[1:4] # 步长默认为1,可以省略不写
print(result)

my_tuple = (0, 1, 2, 3, 4, 5, 6)
result = my_tuple[::2] # 起始和结束不写表示从头到尾
print(result)

my_str = "012, 3, 4,5,6"
result = my_str[:]
print(result)

re_result = my_str[::-1]
print(re_result)

re_result = my_tuple[:2:-1]
print(re_result)
# 可以传递链式巴拉巴拉
my_str = "小蛮腰,是要要要,润要蛮小,冲啊"

result = my_str.split(",")[2].replace("润", "")[::-1]
print(result)

6 collection

Why do you need it!

Let’s take a look at the features:

  • The list is modifiable, supports repeated elements, and is ordered
  • Tuples and strings cannot be modified, support repeated elements and are ordered

Limitations: They both support repeating elements. If the scene requires deduplication of content, lists, tuples, and strings are even more inconvenient. The main feature of collections is that they do not support repeated elements (with built-in deduplication function), and the content is unordered.

Basically the same definitions as lists, tuples, strings, etc.:

  • List:[]
  • tuple:()
  • String:””
  • gather:{}
# 定义集合变量
my_set = {
    
    "yhz", "lr", "xmy", "yhz", "lr", "xmy", "yhz", "lr", "xmy"}
print(my_set)
print(type(my_set))

# 定义空集合
o_set = set()
print(o_set)
print(type(o_set))

o_set = {
    
    }
print(o_set)
print(type(o_set)) # 惊现字典!!!!!

6.1 Common operations on collections

First, the collection is unordered , so the collection does not support subscript index access and does not allow duplicate data to exist . But like the list, it allows modification.

  • Adds the specified element to the collection (the collection itself is modified).集合.add(元素)
  • Removes the specified element from the collection (the collection itself is modified).集合.remove(元素)
  • Randomly removing elements from the collection will result in an element, and at the same time the collection is modified and the element is removed.集合.pop()
  • Clear the collection.集合.clear()
  • Take the difference between the two sets and get a new set. 集合1.difference(集合2)(Get what is present in set 1 but not in set 2, and set 1 and set 2 remain unchanged)
  • Eliminate the difference between two sets. 集合1.difference_update(集合2)(In set 1, delete the same elements as set 2, set 1 is modified, and set 2 remains unchanged)
  • Merge sets, combine the sets to form a new set, and the original set remains unchanged.集合1.union(集合2)
# 添加元素
my_set = {
    
    "yhz", "lr"}
my_set.add("xmy")
print(my_set)

my_set.add("lr") # 添加已有元素会自动去重,相当于没添加
print(my_set)

# 移除元素
my_set.remove("xmy")
print(my_set)

# 随机取出元素
element = my_set.pop()
print(element)
print(my_set)

# 清空集合
my_set.clear()
print(my_set)

# 取两个集合的差集
set_1 = {
    
    1,2,3}
set_2 = {
    
    5,2,0}
set_3 = set_1.difference(set_2)
print(set_1)
print(set_2)
print(set_3)

# 消除两个集合的差集
set_1.difference_update(set_2)
print(set_1)
print(set_2)

# 合并集合
set_1 = {
    
    1,2,3}
set_2 = {
    
    5,2,0}
set_3 = set_1.union(set_2)
print(set_3)

# 统计集合元素数量
print(len(set_3))

Note: Collections do not support subscript indexes, and while loops cannot be used, for loops can be used to traverse.

# 集合的遍历:集合不支持下标索引,不能用 while 循环,可以使用 for 循环遍历
my_set = {
    
    "yhz", "lr", "xmy"}

for elemnet in my_set:
    print(elemnet)

Summarize:

集合.add(元素): Add an element to the collection;

集合.remove(元素): Remove the specified element from the collection;

集合.pop(): Randomly remove an element from the set;

集合.clear(): Clear the collection;

集合1.difference(集合2): Obtain a new set, which contains the difference set of two sets. The contents of the original two sets remain unchanged;

集合1.difference_update(集合2): In set 1, delete the elements that exist in set 2. Set 1 is modified, and set 2 remains unchanged;

集合1.union(集合2): Obtain a new collection containing all elements of the two collections. The contents of the original two collections remain unchanged;

len(集合): Get an integer that records the number of elements in the set.

7 dictionary

Dictionary: Used similarly {}, but the stored elements are key-value pairs{"key": value, "key": value, "key": value} .

Dictionaries, like collections, cannot use subscript indexes , but they can keybe obtained through value.

keyDuplication is not allowed. Repeated addition is equivalent to overwriting the original data.

keyThe sum of dictionaries valuecan be of any data type ( **keynot dictionary**), so dictionaries can be nested.

# 定义字典
my_dict = {
    
    "yhz": 99, "lr": 88, "xmy": 77}
print(my_dict)
print(type(my_dict))

# 定义空字典
o_dict = {
    
    }
print(o_dict)
print(type(o_dict))
o_dict = dict()
print(o_dict)
print(type(o_dict))
# 通过key获取value
score = my_dict["lr"]
print(score)
# 嵌套字典
score_dict = {
    
    
    "yhz":{
    
    
    "history": 33,
    "math": 99,
    "art": 99
    },
    "lr":{
    
    
    "history": 99,
    "math": 66,
    "art": 55
    },
    "xmy":{
    
    
    "history": 33,
    "math": 88,
    "art": 77
    }
}
print(score_dict)

# 从嵌套字典中获取信息
lr_math = score_dict["lr"]["math"]
print(lr_math)

7.1 Common operations on dictionary

  • New elements are added and the dictionary is modified at the same time. Note: Dictionaries cannot be repeated, so performing this operation keyon an existing one is an update .keyvalue字典[key] = value
  • When the element is updated and the dictionary is modified at the same time, the operation is the same as above. The reasons are detailed above.字典[key] = value
  • When an element is deleted, the dictionary is modified and the data of the specified key is deleted.字典.pop(key)
  • The element is cleared and the dictionary is modified.字典.clear()
  • Get them all key.字典.keys()
# 字典的常用操作
my_dict = {
    
    "yhz": 99, "lr": 88, "xmy": 77}

# 新增元素
my_dict["run"] = 66
print(my_dict)

# 更新元素
my_dict["xmy"] = 33
print(my_dict)

# 删除元素
score = my_dict.pop("xmy")
print(score)
print(my_dict)

# 清空元素
my_dict.clear()
print(my_dict)

# 获取全部key
my_dict = {
    
    "yhz": 99, "lr": 88, "xmy": 77}
keys = my_dict.keys()
print(keys)

# 遍历字典
for key in keys:
    print(key)
    print(my_dict[key])

for key in my_dict:
    print(key)
    print(my_dict[key])

# 统计字典内元素数量
count = len(my_dict)
print(count)

Summarize:

字典[Key]: Get the Value value corresponding to the specified Key;

字典[Key]=Value: Add or update key-value pairs;

字典.pop(Key): Take out the Value corresponding to the Key and delete the key-value pair of this Key in the dictionary;

字典.clear(): Clear the dictionary;

字典.keys(): Get all the Kevs of the dictionary, which can be used to traverse the dictionary in a for loop;

len(字典): Count the number of elements in the dictionary.

# 练习:升职加薪
salary = {
    
    
    "wly":{
    
    
    "bm":"kjb",
    "gz":3000,
    "jb":1
    },
    "zjl":{
    
    
    "bm":"scb",
    "gz":50000,
    "jb":2
    },
    "ljj":{
    
    
    "bm":"scb",
    "gz":7000,
    "jb":3
    },
    "zxy":{
    
    
    "bm":"kjb",
    "gz":4000,
    "jb":1
    },
    "ldh":{
    
    
    "bm":"scb",
    "gz":6000,
    "jb":2
    },
}
print(salary)

for key in salary:
    if salary[key]["jb"] == 1:
        salary[key]["gz"] += 1000
        salary[key]["jb"] += 1

print(salary)

8 Summary and comparison of data containers

list tuple string gather dictionary
Number of elements Support multiple Support multiple Support multiple Support multiple Support multiple
element type arbitrary arbitrary characters only arbitrary Key: Value (Key: any type except dictionary; Value: any type)
subscript index support support support not support not support
Repeating elements support support support not support not support
modifiability support not support not support support support
Data in order yes yes yes no no
scenes to be used Modifiable and repeatable batch data recording scenarios Unmodifiable and repeatable batch data recording scenarios Recording scene of a string of characters Non-repeatable data recording scenarios Data recording scenario for retrieving Value using Key

9 Common operations of data containers

Although data containers each have their own characteristics, they also have some common operations.

  1. First of all, in terms of traversal, all five types of data containers support for loop traversal. Lists, tuples, and strings support while loops, but collections and dictionaries do not (cannot subscript indexes). Although there are different forms of traversal, they all support traversal operations .

  2. In addition to the commonality of traversal, there are many general functional methods.

    len(容器): Count the number of elements in the container

    max(容器): The largest element of the statistical container

    min(容器): The smallest element of the statistical container

    list(容器):Convert the given container to a list

    str(容器): Converts the given container to a string

    tuple(容器):Convert the given container to a tuple

    set(容器): Converts the given container to a collection

    Note: Dictionary conversion to string will valuebe retained, and everything else will be left key.

  3. Sort: sorted(容器, reverse=True), sorts the given container. Note: The sorted results will become a list.

# 除遍历外,还有超多通用的功能方法
my_list = [1, 2, 3]
my_tuple = (1, 2, 3, 4)
my_str = "12345"
my_set = {
    
    1, 2, 3, 4, 5}
my_dict = {
    
    "key1": 1, "key2": 2, "key3": 3, "key4": 4, "key5": 5}

print(len(my_list))
print(len(my_tuple))
print(len(my_str))
print(len(my_set))
print(len(my_dict))

print(max(my_list))
print(max(my_tuple))
print(max(my_str))
print(max(my_set))
print(max(my_dict))

print(min(my_list))
print(min(my_tuple))
print(min(my_str))
print(min(my_set))
print(min(my_dict))
print(list(my_str))
print(type(list(my_str)))

print(str(my_list))
print(type(str(my_list)))

print(tuple(my_set))
print(type(tuple(my_set)))

print(set(my_dict))
print(type(set(my_dict)))
my_set = {
    
    4, 5, 3, 7, 0, 2}
print(sorted(my_set))
print(sorted(my_set, reverse=True))

Summarize:

General for loop: traverse the container (the dictionary traverses the key);

max(): The largest element in the container;

min(): The smallest element in the container;

len():The number of container elements;

list():Convert to list;

tuple():Convert to tuple;

str(): Convert to string;

set():Convert to set;

sorted(序列, [reverse=True]): Sort, reverse=Trueindicating that a sorted list will be obtained in descending order.

Guess you like

Origin blog.csdn.net/weixin_43843918/article/details/131444701