[Revisiting Python] 1. The built-in data structure in Python

foreword

I plan to review the basics systematically again. This series is mainly to review the python language. The knowledge points that will not be involved are too deep, mainly some basic but easily overlooked things. I didn’t take notes during the first study, and I didn’t make a good summary. Here is a review and summary, so that you don’t need it when you use it later It's always Baidu.

This part summarizes the common data structure types of python, mainly lists, dictionaries, sets, and tuples.

Mainly introduce their differences and specific operations.

The next section covers String strings.

1. List: [], list()

1.0. Overview of list features and operations

Features of the list

sequence type: list

  1. is a variable sequence;
  2. The elements in the list are ordered;
  3. Each element in the list corresponds to an index index, and the corresponding element can be located according to the index;
  4. Lists can store repeated elements;
  5. Lists can store elements of any type;
  6. The list has no fixed length, and it can dynamically allocate memory space in real time according to the number of elements;

Operation overview

operate describe
[]、list() create list
x=ls.index(idx,start,end) Find the list in the start-end range according to index
ls.append(x) Add an element x to the end of the list ls
ls.insert(i,x) Adds the element x at the i-th position of the list ls
ls.extend() Add several elements at the end of the list ls, 1 or more
ls.pop() Delete the element at the specified index position, the default is to delete the last -1, 0 means delete the first element
ls.remove(x) removes the first x element that occurs in the list
ls.clear() clear the list
of them delete list completely
ls[idx] = new_value modify list elements
ls.sort() Default ascending order, in-place ((that is, the list itself is modified to return None)) and stable sorting (keep the order of two equal elements unchanged), the reverse attribute can be sorted in descending order
sorted(ls) Python built-in function, returns a new list, ascending by default, reverse attribute can be sorted in descending order

1.1. List creation

# 创建列表
# 1、[]创建列表
l1 = ['Hello', 'World', 'Python']
print(l1)

# 2、内置函数list创建列表
l2 = list(l1)
print(l2)

# 3、列表生成式
l3 = [i for i in range(1, 11)]
print(l3)

1.2. List search

Because each element in the list has an index index corresponding to one of them, the corresponding index value is found according to the element.

If the lists have identical elements, then only the index of the first element of the identical element is returned.

语法:列表.index('要获取索引的元素值',起始位置,结束位置)

l1 = ['hello', 'world', 'python', 'hello', 'world', 'python']
print(l1.index('world'))          # 1
print(l1.index('world', 2, 5))  # 4

1.3. List addition

method describe
ls.append(x) Add an element x to the end of the list ls
ls.insert(i,x) Adds the element x at the i-th position of the list ls
ls.extend() Add several elements at the end of the list ls, 1 or more
ls1 = [10, 20, 30]
ls2 = ['hello', 'world']

ls1.append(100)
print(ls1)  # [10, 20, 30, 100]

ls1.extend(ls2)
print(ls1)  # [10, 20, 30, 100]

ls1.insert(4, 'python')
print(ls1)  # [10, 20, 30, 100, 'python', 'hello', 'world']

1.4. List deletion

method describe
ls.pop() Delete the element at the specified index position, the default is to delete the last -1, 0 means delete the first element
ls.remove(x) removes the first x element that occurs in the list
ls.clear() clear the list
of them delete list completely
ls = [1, 2, 3, 2, 4, 5, 6, 7, 8, 9]
ls.remove(2)
print(ls)  # [1, 3, 2, 4, 5, 6, 7, 8, 9]

ls.pop(7) 
print(ls)  # [1, 3, 2, 4, 5, 6, 7, 9]
ls.pop()
print(ls)  # [1, 3, 2, 4, 5, 6, 7]
ls.pop(0)
print(ls)  # [3, 2, 4, 5, 6, 7]

ls.clear()
print(ls)   # []

del ls
# print(ls)   # 报错

1.5. List modification

The list is mutable, and there is no need for any method to modify the list, just modify the value on the corresponding index directly.

ls = [1, 2, 3, 4]
ls[2] = 100
print(ls)  # [1, 2, 100, 4]

1.6. List sorting

method describe
ls.sort() Default ascending order, in-place ((that is, the list itself is modified to return None)) and stable sorting (keep the order of two equal elements unchanged), the reverse attribute can be sorted in descending order
sorted(ls) Python built-in function, returns a new list, ascending by default, reverse attribute can be sorted in descending order
ls = [1, 3, 4, 2]
ls.sort()
print(ls)   # [1, 2, 3, 4]
ls.sort(reverse=True)
print(ls)   # [4, 3, 2, 1]

ls1 = [1, 3, 4, 2]
ls2 = sorted(ls1)
print(ls2)  # [1, 2, 3, 4]
ls3 = sorted(ls1, reverse=True)
print(ls3)  # [4, 3, 2, 1]

2. Dictionary: {}, dict()

Mapping type: dictionary

2.0. Overview of dictionary features and operations

Features of the dictionary

  1. It is also a mutable sequence that stores data in the form of key-value pairs;
  2. One-to-one correspondence between key and value, the key cannot be repeated, but the value can be repeated;
  3. The elements in the dictionary are unordered;
  4. The dictionary will waste a lot of memory, it is a data structure that trades space for time, but the query speed is very fast;

Operation overview

operate describe
{}、dict () create dictionary
zip() Can create a dictionary, take an iterable object as a parameter, pack the corresponding elements in the object into a tuple, and then return a list of these tuples
d[key]、d.get(key,default) Get the value val of the dictionary d according to the key key, return the corresponding value, or return the default value if it does not exist
d.keys() Return information about all keys in dictionary d
d.values() Return information about all values ​​of dictionary d
d.items() Return all key-value pairs of dictionary d, this function can be used to traverse the dictionary
d['key']=val Add/modify new key-value pairs
del d[key] 删除字典d的某个键值对
val = d.pop(key, default) 删除字典d的某个键值对,并返回这个键对应的值,如果不存在的话返回默认值
key, val = d.popitem() 删除并返回出 最后一个元素的键和值
d.clear() 清空整个字典
len(d) 字典d的元素个数
max(d) 字典d的键的最大值
min(d) 字典d的键的最小值

2.1、字典创建

# 1、使用花括号{}创建
scores = {'章三': 29, '李四': 10, '王五': 40}
print(scores)   # {'章三': 29, '李四': 10, '王五': 40}
print(type(scores))  # <class 'dict'>

# 2、内置函数dict(键1=值1, 键2=值2)
people = dict(name='章三', age=20)
print(people)  # {'name': '章三', 'age': 20}

# 3、zip() 将可迭代对象作为参数,将对象中对应的元素打包成一个元组,然后返回由这些元组组成的列表
keys = ['fruits', 'books', 'others']
vals = [96, 78, 85]
d1 = {key: val for key, val in zip(keys, vals)}
print(d1)  # {'fruits': 96, 'books': 78, 'others': 85}

d2 = dict(zip(keys, vals)) 
print(d2)  # {'fruits': 96, 'books': 78, 'others': 85}

2.2、字典查找

# 1、使用[]直接查找
scores = {'章三': 29, '李四': 10, '王五': 40}
print(scores['李四'])       # 10

# 2、使用get()方法查找   字典1.get(键1,值1)  在字典1中查找键1的值,如果不存在就返回值1
print(scores.get('李四'))   # 10
print(scores.get('章三'))   # 29
print(scores.get('麻子'))   # None
print(scores.get('麻子', 100))   # 100

# 3、获取所有的键和值
print(scores.keys())          # dict_keys(['章三', '李四', '王五'])
print(list(scores.keys()))    # ['章三', '李四', '王五']
print(scores.values())        # dict_values([29, 10, 40])
print(list(scores.values()))  # [29, 10, 40]
print(scores.items())  # dict_items([('章三', 29), ('李四', 10), ('王五', 40)])

2.3、字典添加

scores = {'章三': 29, '李四': 10, '王五': 40}
scores['陈六'] = 20
print(scores)  # {'章三': 29, '李四': 10, '王五': 40, '陈六': 20}

2.4、字典删除

# 1、删除某个键值对
scores = {'章三': 29, '李四': 10, '王五': 40, '老六': 99}
del scores['李四']
print(scores)  # {'章三': 29, '王五': 40, '老六': 99}

# 2、d.pop(key,default=val) pop掉键key和对应的值 并返回对应的值  如果不存在返回默认值
val = scores.pop('章三', 100)
print(val)  # 29
print(scores)   # {'王五': 40, '老六': 99}

# d.popitem() pop出最后一个元素的键和值
key, val = scores.popitem()
print(key, val)  # 老六 99
print(scores)    # {'王五': 40}

# 3、清除整个字典
scores.clear()
print(scores)  # {}

2.5、字典修改

scores = {'章三': 29, '李四': 10, '王五': 40}
scores['李四'] = 20
print(scores)  # {'章三': 29, '李四': 20, '王五': 40}

2.6、字典遍历

for item in scores:
    print(item, scores[item])

for key, value in scores.items():
    print(key, value)

三、元组:()、tuple()

3.0、元组的特点和操作总览

元组的特点

  1. 元组是一个不可变序列,元组有增加操作,但是没有删、改的操作;
  2. 相较于列表,元组的读取速度更快,占用内存空间更小,并且可以作为字典的key去使用;
  3. (4)和(4,)是不一样的,前者是int类型,后者才是元组类型;

元组操作总览

操作 描述
()、tuple() 创建元组
t[idx] 查找元组

3.1、元组创建

# 1、()创建 注意只包含一个元素的时候需要在最后加一个逗号
t1 = ('python', 'java')
print(t1)        # ('python', 'java')
print(type(t1))  # <class 'tuple'>

t2 = ('python')
print(t2)        # python
print(type(t2))  # <class 'str'>
t3 = ('python', )
print(t3)        # ('python',)
print(type(t3))  # <class 'tuple'>

# 2、内置函数tuple()创建
t4 = tuple(('python', 'java'))
print(t4)        # ('python', 'java')
print(type(t4))  # <class 'tuple'>

3.2、元组的查找和遍历

t = ('hello', 'world', 'python')
print(t[1])  # world

for item in t: 
    print(item, end=' ')  # hello world python 

3.3、元组添加

t1 = (1, 2, 3, 4)
t1 += (5, )
print(t1)  # (1, 2, 3, 4, 5)

四、集合:{}、set()

4.0、集合的特点和操作总览

集合的特点

  1. 集合中的元素都是无序的,且元素都是不可重复的,所以{1,2,3} 和{3,2,1}是同一个集合;
  2. 集合是没用value的字典;
  3. 和列表、字典一样都是可变序列,但是集合是没法修改的,因为集合是无序的,无法根据index对集合进行修改,只能删除掉再重新添加;

操作总览

操作 描述
{}、set() 创建集合
s.add(x) 集合s添加一个元素x
s2.uptate(s1) 集合s2添加多个元素s1
s.remove(x) 集合s删除元素x,不存在就报错
s.discard(x) 集合s删除元素x,不存在也不会报错
s.pop() 集合s删除任意一个元素,因为集合是无序的
s.clear() 清空集合s
len(s) 集合s中的元素个数

4.1、集合创建

# 1、{}创建集合
s1 = {1, 2, 3, 4, 5, 6}
print(s1)  # {1, 2, 3, 4, 5, 6}

# 2、内置函数set()创建集合
s2 = set([1, 2, 3, 4, 5, 6])
print(s2)  # {1, 2, 3, 4, 5, 6}

s3 = set('python')
print(s3)  # {'h', 'n', 'o', 'y', 'p', 't'}

4.2、集合添加

# 1、s.add(x) 添加一个元素x 
s1 = {1, 2, 3, 4, 5, 6}
print(s1)  # {1, 2, 3, 4, 5, 6}
s1.add(7)
print(s1)  # {1, 2, 3, 4, 5, 6, 7}

# 2、s2.update(s1)  添加多个元素
s1.update((7, 8, 9))
print(s1)  # {1, 2, 3, 4, 5, 6, 7, 8, 9}

4.3、集合删除

# 1、s.remove(x) 一次删除一个元素x  不存在即报错 
s1 = {1, 2, 3, 4, 5, 6}
s1.remove(3)
print(s1)  # {1, 2, 4, 5, 6}
# s1.remove(7)  报错

# 2、s.discard(x) 一次删除一个元素x  不存在不会报错  不怎么用
s1.discard(4)
print(s1)  # {1, 2, 5, 6}
s1.discard(7)  # 不报错
print(s1)  # {1, 2, 5, 6}

# 3、s.pop()  一次删除任一个元素
s1.pop()
print(s1)

# 4、s.clear() 清空集合
s1.clear()
print(s1)  # set()

五、总结区别

项目 列表 集合 字典 元组(只读)
创建 []、list() {}、set() {}、dict() ()、tuple
存储方式 键(不能重复) 键值对(键不可以重复)
是否有序 有序 无序 无序 有序
查找元素 value = ls[index] value = d[key] value = t[index]
添加元素 append、insert、extend add、update d[key] = value t1 += t2
删除元素 pop、remove remove、discard del d[key]、d.pop(key,default=val) 、d.popitem()
修改元素 ls[index]=new_value d[key]=new_value

Reference

CSDN: 【重温Python基础】最全Python基础知识点,加班熬夜花了三天终于总结出来了,非常详细

书籍:Python进阶编程

おすすめ

転載: blog.csdn.net/qq_38253797/article/details/127245966