Home  >  Article  >  Backend Development  >  Detailed introduction to Python3 data structure knowledge points

Detailed introduction to Python3 data structure knowledge points

WBOY
WBOYforward
2022-04-06 18:27:411847browse

This article brings you relevant knowledge about python, which mainly introduces issues related to data structures, including numbers, strings, lists, tuples, dictionaries, etc. Content, I hope it will be helpful to everyone.

Detailed introduction to Python3 data structure knowledge points

Recommended learning: python video tutorial

Number

  • Integer type ( int) - often called an integer or integer, a positive or negative integer without a decimal point. Python3 integers have no size limit and can be used as Long types. Boolean is a subtype of integer.

  • Floating point type (float) - The floating point type consists of an integer part and a decimal part. The floating point type can also be expressed using scientific notation (2.5e2 = 2.5 x 102 = 250)

  • Complex number ((complex)) - A complex number consists of a real part and an imaginary part. It can be represented by a bj, or complex(a,b). The real part a and the imaginary part of the complex number b are all floating point types.

Number type conversion

  • int(x) Convert x to an integer.

  • float(x) Convert x to a floating point number.

  • complex(x) Convert x to a complex number, with the real part being x and the imaginary part being 0.

  • complex(x, y) Converts x and y to a complex number, with the real part being x and the imaginary part being y. x and y are numeric expressions.

Number operation

# + - * / %(取余) **(幂运算)
# 整数除法中,除法 / 总是返回一个浮点数,
# 如果只想得到整数的结果,丢弃可能的分数部分,可以使用运算符 //
print(8 / 5)  # 1.6
print(8 // 5)  # 1
# 注意:// 得到的并不一定是整数类型的数,它与分母分子的数据类型有关系
print(8 // 5.0)  # 1.0
# 使用 ** 操作来进行幂运算
print(5 ** 2)  # 5的平方 25

String str

Query of string

  • index(): Find the position where the substring substr appears for the first time. If the substring being searched does not exist, a ValueErrorrindex() exception will be thrown.

  • rindex(): Find the last occurrence of the substring substr. position, if the searched substring does not exist, a ValueError() exception will be thrown

  • find(): Find the position where the substring substr first appears. If the searched substring When the string does not exist, it returns -1

  • rfind(): Finds the last occurrence of the substring substr. If the searched substring does not exist, it returns -1

s = 'hello, hello'
print(s.index('lo'))  # 3
print(s.find('lo'))  # 3
print(s.find('k'))  # -1
print(s.rindex('lo'))  # 10
print(s.rfind('lo'))  # 10

String case conversion

  • upper(): Convert all characters in the string to uppercase letters

  • lower(): Convert all the characters in the string to lowercase letters

  • swapcase(): Convert all the uppercase letters in the string to lowercase letters, and convert all Convert lowercase letters to uppercase letters

  • capitalize(): Convert the first character to uppercase, and convert the remaining characters to lowercase

  • title(): Convert the first character of each word to uppercase, and convert the remaining characters of each word to lowercase

s = 'hello, Python'
print(s.upper())  # HELLO, PYTHON
print(s.lower())  # hello, python
print(s.swapcase())  # HELLO, pYTHON
print(s.capitalize())  # Hello, python
print(s.title())  # Hello, Python

String alignment

  • center(): Center-aligned, the first parameter specifies the width, the second parameter specifies the filler, the default is a space, if the set width is smaller than the actual width, the original string is returned

  • ljust(): Left-aligned, the first parameter specifies the width, the second parameter specifies the filler, the default is a space, if the set width is smaller than the actual width, the original string is returned

  • rjust(): Right-aligned, the first parameter specifies the width, the second parameter specifies the filler, the default is a space, if the set width is smaller than the actual width, the original string is returned

  • zfill(): Right-aligned, filled with 0 on the left. This method only receives one parameter, which is used to specify the width of the string. If the specified width is less than or equal to the length of the string, the string itself is returned

s = 'hello,Python'
'''居中对齐'''
print(s.center(20, '*'))  # ****hello,Python****
'''左对齐 '''
print(s.ljust(20, '*'))  # hello,Python********
print(s.ljust(5, '*'))  # hello,Python
'''右对齐'''
print(s.rjust(20, '*'))  # ********hello,Python
'''右对齐,使用0进行填充'''
print(s.zfill(20))  # 00000000hello,Python
print('-1005'.zfill(8))  # -0001005

String splitting, slicing

Split

  • split(): Split from the left side of the string
  • rsplit(): Split from the right side of the string
    • The default splitting character is a space, and the return value is a list
    • Specify the split string through the parameter sep Splitting character
    • The parameter maxsplit specifies the maximum number of splits when splitting a character string. After the maximum number of splits, the remaining substrings will be separately used as a part
s = 'hello word Python'
print(s.split())  # ['hello', 'word', 'Python']
s1 = 'hello|word|Python'
print(s1.split(sep='|'))  # ['hello', 'word', 'Python']
print(s1.split('|', 1))  # ['hello', 'word|Python'] # 左侧开始
print(s1.rsplit('|', 1))  # ['hello|word', 'Python'] # 右侧开始

Slicing

s = 'hello,world'
print(s[:5])  # hello 从索引0开始,到4结束
print(s[6:])  # world 从索引6开始,到最后一个元素
print(s[1:5:1])  # ello 从索引1开始,到4结束,步长为1
print(s[::2])  # hlowrd 从开始到结束,步长为2
print(s[::-1])  # dlrow,olleh 步长为负数,从最后一个元素(索引-1)开始,到第一个元素结束
print(s[-6::1])  # ,world 从索引-6开始,到最后一个结束

String judgment related

  • isidentifier(): Determine whether the specified string is a legal identifier
  • isspace(): Determines whether the specified string is entirely composed of whitespace characters (carriage return, line feed, horizontal tab characters)
  • isalpha(): Determines whether the specified string is entirely composed of Letter composition
  • isdecimal(): Determine whether the specified string consists entirely of decimal digits
  • isnumeric(): Determine whether the specified string consists entirely of decimal digits
  • isalnum (): Determine whether the specified string consists entirely of letters and numbers

Other string operations

String replacement

  • replace()
s = 'hello,Python,Python,Python'
print(s.replace('Python', 'Java'))  # 默认全部替换 hello,Java,Java,Java
print(s.replace('Python', 'Java', 2))  # 设置替换个数 hello,Java,Java,Python

String connection

  • join()
lst = ['hello', 'java', 'Python']
print(','.join(lst))  # hello,java,Python
print('|'.join(lst))  # hello|java|Python

Formatted string output

  • % placeholder: add % before output, use parentheses and commas for multiple parameters
    • %s string
    • %i or %d integer
    • -%f floating point number
  • {} placeholder: call the format() method
  • f-string: write the variable in {}
name = '张三'
age = 20
print('我叫%s, 今年%d岁' % (name, age))
print('我叫{0}, 今年{1}岁,小名也叫{0}'.format(name, age))
print(f'我叫{name}, 今年{age}岁')
# 我叫张三, 今年20岁
# 我叫张三, 今年20岁,小名也叫张三
# 我叫张三, 今年20岁

Set the width and precision of numbers

# 设置数字的宽度和精度
'''%占位'''
print('%10d' % 99)  # 10表示宽度
print('%.3f' % 3.1415926)  # .3f表示小数点后3位
print('%10.3f' % 3.1415926)  # 同时设置宽度和精度
'''{}占位 需要使用:开始'''
print('{:.3}'.format(3.1415926))  # .3表示3位有效数字
print('{:.3f}'.format(3.1415926))  # .3f表示小数点后3位
print('{:10.3f}'.format(3.1415926))  # .3f表示小数点后3位
#        99
#3.142
#     3.142
#3.14
#3.142
#     3.142

String encoding

s = '但愿人长久'
# 编码 将字符串转换成byte(二进制)数据
print(s.encode(encoding='gbk')) #gbk,中文占用2个字节
print(s.encode(encoding='utf-8')) #utf-8,中文占用3个字节
# 解码 将byte(二进制)转换成字符串数据
# 编码与解码中,encoding方式需要一致
byte = s.encode(encoding='gbk')
print(byte.decode(encoding='gbk'))
# b'\xb5\xab\xd4\xb8\xc8\xcb\xb3\xa4\xbe\xc3'
# b'\xe4\xbd\x86\xe6\x84\xbf\xe4\xba\xba\xe9\x95\xbf\xe4\xb9\x85'
# 但愿人长久

List list

Characteristics of lists

  • Ordered sequence

  • Index mapping unique data

  • 可以存储重复数据

  • 任意数据类型混存

  • 根据需要动态分配和回收内存

列表的创建

  • []:使用中括号
  • list():使用内置函数list()
  • 列表生成式
    • 语法格式:[i*i for i in range(i, 10)]

    • 解释:i表示自定义变量,i*i表示列表元素的表达式,range(i, 10)表示可迭代对象

      print([i * i for i in range(1, 10)])# [1, 4, 9, 16, 25, 36, 49, 64, 81]

列表元素的查询

  1. 判断指定元素在列表中是否存在
in / not in
  1. 列表元素的遍历
for item in list:
	print(item)
  1. 查询元素索引
list.index(item)
  1. 获取元素
list = [1, 4, 9, 16, 25, 36, 49, 64, 81]print(list[3])  # 16print(list[3:6])    # [16, 25, 36]

列表元素的增加

  • append():在列表的末尾添加一个元素

  • extend():在列表的末尾至少添加一个元素

  • insert0:在列表的指定位置添加一个元素

  • 切片:在列表的指定位置添加至少一个元素

列表元素的删除

  • rerove():一次删除一个元素,
    重复元素只删除第一个,
    元素不存在抛出ValceError异常

  • pop():删除一个指定索引位置上的元素,
    指定索引不存在抛出IndexError异常,
    不指定索引,删除列表中最后一个元素

  • 切片:一次至少删除一个元素

  • clear0:清空列表

  • del:删除列表

列表元素的排序

  • sort(),列表中的所有元素默认按照从小到大的顺序进行排序,可以指定reverse= True,进行降序排序,是对原列表的操作。
list.sort()
  • sorted(),可以指定reverse—True,进行降序排序,原列表不发生改变,产生新的列表。
sorted(list)

知识点总结

Detailed introduction to Python3 data structure knowledge points

元组 tuple

元组的特点

Python的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号

元组的创建

  • 直接使用小括号(), 小括号可以省略
t = ('Python', 'hello', 90)
  • 使用内置函数tuple(), 若有多个元素必须加小括号
tuple(('Python', 'hello', 90))
  • 只包含一个元素的元组,需要使用小括号和逗号
t = (10,)

知识点总结

Detailed introduction to Python3 data structure knowledge points

字典 dict

字典的特点

  • 以键值对的方式存储,key唯一
  • key必须是不可变对象
  • 字典是可变序列
  • 字典是无序序列 (注意:自Python3.7本后,dict 对象的插入顺序保留性质已被声明为 Python 语言规范的正式部分。即,Python3.7之后,字典是有序序列,顺序为字典的插入顺序)

字典的创建

  • {}:使用花括号
  • 使用内置函数dict()
  • zip():字典生成式
items = ['fruits', 'Books', 'Others']
prices = [12, 36, 44]
d = {item.upper(): price for item, price in zip(items, prices)}
print(d)    # {'FRUITS': 12, 'BOOKS': 36, 'OTHERS': 44}

字典元素的获取

  • []:[]取值
    scores[‘张三’],若key不存在,抛出keyError异常
  • get():get()方法取值,若key不存在,返回None,还可以设置默认返回值

字典元素的新增

user = {"id": 1, "name": "zhangsan"}
user["age"] = 25
print(user)  # {'id': 1, 'name': 'zhangsan', 'age': 25}

字典元素的修改

user = {"id": 1, "name": "zhangsan", "age": 25}
user["age"] = 18
print(user)  # {'id': 1, 'name': 'zhangsan', 'age': 18}

字典元素的删除

  • del :删除指定的键值对或者删除字典
user = {"id": 1, "name": "zhangsan"}del user["id"]print(user)	# {'name': 'zhangsan'}del user
  • claer():清空字典中的元素
user = {"id": 1, "name": "zhangsan"}user.clear()print(user)  # {}

获取字典视图

  • keys():获取字典中所有key
  • values():获取字典中所有value
  • items():获取字典中所有key,value键值对

字典元素的遍历

  • 遍历key,再通过key获取value
scores = {'张三': 100, '李四': 95, '王五': 88}for name in scores:
    print(name, scores[name])
  • 通过items()方法,同时遍历key,value
scores = {'张三': 100, '李四': 95, '王五': 88}for name, score in scores.items():
    print(name, score)

知识点总结

Detailed introduction to Python3 data structure knowledge points

集合 set

集合的特点

  • 集合是可变序列
  • 集合是没有value的字典
  • 集合中元素不重复
  • 集合中元素是无序的

集合的创建

  • {}
s = {'Python', 'hello', 90}
  • 内置函数set()
print(set("Python"))print(set(range(1,6)))print(set([3, 4, 7]))print(set((3, 2, 0)))print(set({"a", "b", "c"}))# 定义空集合:set()print(set())
  • 集合生成式
print({i * i for i in range(1, 10)})# {64, 1, 4, 36, 9, 16, 49, 81, 25}

集合的操作

  1. 集合元素的判断操作
  • in / not in
  1. 集合元素的新增操作
  • add():一次添中一个元素
  • update(:)添加多个元素
  1. 集合元素的删除操作
  • remove():删除一个指定元素,如果指定的元素不存在抛出KeyError
  • discard(:)删除一个指定元素,如果指定的元素不存在不抛异常
  • pop():随机删除一个元素
  • clear():清空集合

集合间的关系

  1. 两个集合是否相等:可以使用运算符 == 或 != 进行判断,只要元素相同就相等

  2. 一个集合是否是另一个集合的子集:issubset()

s1 = {10, 20, 30, 40, 50, 60}s2 = {10, 30, 40}s3 = {10, 70}print(s2.issubset(s1))  
# Trueprint(s3.issubset(s1))  # False
  1. 一个集合是否是另一个集合的超集:issuperset()
print(s1.issuperset(s2))  # Trueprint(s1.issuperset(s3))  # False
  1. 两个集合是否无交集:isdisjoint()
s1 = {10, 20, 30, 40, 50, 60}s2 = {10, 30, 40}s3 = {20, 70}print(s1.isdisjoint(s2))  
# False 有交集print(s3.isdisjoint(s2))  # True  无交集

集合的数学操作

  1. 交集: intersection() 与 &等价,两个集合的交集
s1 = {10, 20, 30, 40}s2 = {20, 30, 40, 50, 60}print(s1.intersection(s2))  # {40, 20, 30}print(s1 & s2)  # {40, 20, 30}
  1. 并集: union() 与 | 等价,两个集合的并集
print(s1.union(s2))  # {40, 10, 50, 20, 60, 30}print(s1 | s2)  # {40, 10, 50, 20, 60, 30}
  1. 差集: difference() 与 - 等价
print(s2.difference(s1))  # {50, 60}print(s2 - s1)  # {50, 60}
  1. 对称差集:symmetric_difference() 与 ^ 等价
print(s2.symmetric_difference(s1))  # {10, 50, 60}print(s2 ^ s1)  # {10, 50, 60}

知识点总结

Detailed introduction to Python3 data structure knowledge points

列表、元组、字典、集合总结

推荐学习:python教程

The above is the detailed content of Detailed introduction to Python3 data structure knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete