【1.0】Python中级之数据类型的内置方法

【一】数据类型内置方法介绍

  • 数据类型是用来记录事物状态的,而事物的状态是不断变化的(如:一个人年龄的增长(操作int类型)
  • 单个人名的修改(操作str类型),学生列表中增加学生(操作list类型)等),这意味着我们在开发程序时需要频繁对数据进行操作
  • 为了提升我们的开发效率
  • python针对这些常用的操作,为每一种数据类型内置了一系列方法。

【二】数字类型

【1】整数类型(int)

(1)整数类型定义

  • 整数类型是Python中的一种基本数据类型,用于表示整数。
  • 在Python中,整数类型是不可变的,即一旦创建,其值不能被修改。

(2)定义

  • 整数类型可以直接使用数字进行定义
num = 42

(3)内置方法

  • int.bit_length()
    • 返回整数的二进制表示中最高位的位数,不包括符号和前导零。
num = 42 bit_length = num.bit_length() print(bit_length) # 输出:6
  • int.to_bytes(length, byteorder, signed)
    • 将整数转换为字节数组。
    • 参数length指定生成的字节数组的长度,byteorder指定字节顺序,signed指定是否考虑整数的符号。
num = 42 byte_array = num.to_bytes(2, byteorder='big', signed=False) print(byte_array) # 输出:b'\x00*'
  • int.from_bytes(bytes, byteorder, signed)
    • 将字节数组转换为整数。
    • 参数bytes是输入的字节数组,byteorder指定字节顺序,signed指定是否考虑整数的符号。
byte_array = b'\x00*' num = int.from_bytes(byte_array, byteorder='big', signed=False) print(num) # 输出:42
  • int.__add__(other)
    • 实现整数的加法运算。
num1 = 42 num2 = 10 result = num1.__add__(num2) print(result) # 输出:52
  • int.__sub__(other)
    • 实现整数的减法运算。
num1 = 42 num2 = 10 result = num1.__sub__(num2) print(result) # 输出:32
  • int.__mul__(other)
    • 实现整数的乘法运算。
num1 = 42 num2 = 10 result = num1.__mul__(num2) print(result) # 输出:420
  • int.__truediv__(other)
    • 实现整数的真除法运算。
num1 = 42 num2 = 10 result = num1.__truediv__(num2) print(result) # 输出:4.2
  • int.__floordiv__(other)
    • 实现整数的整除法运算。
num1 = 42 num2 = 10 result = num1.__floordiv__(num2) print(result) # 输出:4
  • int.__mod__(other)
    • 实现整数的取模运算。
num1 = 42 num2 = 10 result = num1.__mod__(num2) print(result) # 输出:2
  • int.__pow__(other, modulo=None)
    • 实现整数的幂运算。
num1 = 2 num2 = 3 result = num1.__pow__(num2) print(result) # 输出:8

(4)类型强转

  • 可以将由纯整数构成的字符串直接转换成整型
    • 若包含其他任意非整数符号
    • 则会报错
s = '123' res = int(s) print(res, type(res)) # 123 <class 'int'> print(int('12.3')) # 错误演示:字符串内包含了非整数符号. ''' Traceback (most recent call last): File "E:\PythonProjects\02用户交互.py", line 40, in <module> print(int('12.3')) # 错误演示:字符串内包含了非整数符号. ValueError: invalid literal for int() with base 10: '12.3' '''

(5)进制转换

  • 在Python中,整数类型提供了一些方法来进行进制转换,主要涉及到二进制、八进制、十六进制。

[1]十进制转二进制:bin()

  • 将整数转换为二进制表示,返回一个字符串。
num = 42 binary_representation = bin(num) print(binary_representation) # 输出:'0b101010'

[2]十进制转八进制:oct()

  • 将整数转换为八进制表示,返回一个字符串。
num = 42 octal_representation = oct(num) print(octal_representation) # 输出:'0o52'

[3]十进制转十六进制:hex()

  • 将整数转换为十六进制表示,返回一个字符串。
num = 42 hexadecimal_representation = hex(num) print(hexadecimal_representation) # 输出:'0x2a'

[4]其它进制转十进制:int()

  • int() 函数支持将不同进制的字符串转换为十进制整数。主要的进制包括:

    • 二进制(以 '0b' 或 '0B' 开头)

    • 八进制(以 '0o' 或 '0O' 开头)

    • 十六进制(以 '0x' 或 '0X' 开头)

  • 你可以根据需要选择不同的进制进行转换。

binary_str = '0b101010' decimal_num = int(binary_str, 2) print(decimal_num) # 输出:42 octal_str = '0o52' decimal_num = int(octal_str, 8) print(decimal_num) # 输出:42 hexadecimal_str = '0x2a' decimal_num = int(hexadecimal_str, 16) print(decimal_num) # 输出:42
  • 在这些例子中,字符串的前缀表明了不同的进制

【2】浮点类型(float)

(1)浮点类型定义

  • 浮点类型是一种表示有小数部分的数字的数据类型。
  • 在Python中,可以使用小数点表示浮点数。

(2)定义

float_number = 3.14

(3)内置方法

  • 浮点类型的内置方法包括各种数学运算,例如加法、减法、乘法和除法。
  • 此外,还有一些与浮点数相关的函数,如取整函数 round()
# 加法 result_add = 3.14 + 2.5 # 减法 result_subtract = 5.7 - 1.2 # 乘法 result_multiply = 2.0 * 3.5 # 除法 result_divide = 8.0 / 4.0 # 取整 rounded_number = round(3.14159)
  • 这些方法和运算符都可用于浮点数的处理。值得注意的是,由于计算机存储浮点数的方式,可能存在一些精度问题。

(4)类型强转

  • 类型强转,即将一个数据类型转换为另一个数据类型
  • 。在Python中,可以使用内置函数来进行类型强转。
# 将整数转换为浮点数 integer_number = 42 float_number = float(integer_number) # 将浮点数转换为整数 float_number = 3.14 integer_number = int(float_number)
  • 在上述例子中,float() 函数将整数转换为浮点数,而 int() 函数将浮点数转换为整数。
  • 类型强转在处理不同类型的数据时非常常见,确保数据在执行某些操作时具有相同的类型,以避免出现错误。

【3】判断数字类型

(1)数字类型说明

num1 = b'4' # bytes num2 = '4' # unicode,Python 3 中不需要在字符串前加 'u' num3 = '四' # 中文数字 num4 = 'Ⅳ' # 罗马数字

(2)判断数字类型(isdigit)

# isdigit: bytes, unicode print(num1.isdigit()) # True print(num2.isdigit()) # True print(num3.isdigit()) # False print(num4.isdigit()) # False

(3)判断小数类型(isdecimal)

# isdecimal: unicode(bytes 类型没有 isdecimal 方法) print(num2.isdecimal()) # True print(num3.isdecimal()) # False print(num4.isdecimal()) # False

(4)判断数字类型(isnumeric)

# isnumeric: unicode, 中文数字, 罗马数字(bytes 类型没有 isnumeric 方法) print(num2.isnumeric()) # True print(num3.isnumeric()) # True print(num4.isnumeric()) # True

(5)无法判断浮点数

# 这三种方法无法判断浮点数 num5 = '4.3' print(num5.isdigit()) # False print(num5.isdecimal()) # False print(num5.isnumeric()) # False

【三】字符串类型(str)

【1】字符串类型定义

  • 字符串是由字符组成的,可以包含字母、数字、标点符号、空格等字符。
  • 在Python中,字符串类型使用单引号或双引号来定义。
# 使用单引号定义字符串 single_quoted_str = 'Hello, World!' # 使用双引号定义字符串 double_quoted_str = "Hello, Python!"
  • 字符串还可以使用三引号(单引号或双引号)定义多行字符串
multi_line_str = ''' This is a multi-line string in Python. '''

【2】定义

【3】内置方法(优先)

(0)字符串拼接

  • 字符串拼接是将多个字符串连接在一起形成一个新的字符串。
  • 可以使用 + 运算符来实现字符串拼接。
str1 = 'Hello,' str2 = 'World!' result_str = str1 + ' ' + str2 print(result_str) # 输出: Hello, World!

(1)索引取值

[1]正索引取值

  • 字符串中的每个字符都有一个索引,正索引从左到右依次增加
text = 'Python' first_char = text[0] print(first_char) # 输出: P

[2]反索引取值

  • 反索引从右到左依次增加,最右边的字符索引为 -1。
text = 'Python' last_char = text[-1] print(last_char) # 输出: n

[3]只能取值,不能修改

str1 = 'hello python!' str1[0]='H' ''' Traceback (most recent call last): File "E:\PythonProjects\02用户交互.py", line 58, in <module> str1[0]='H' # 报错TypeError TypeError: 'str' object does not support item assignment '''

(2)切片(顾头不顾尾)

[1]切片顾头不顾尾

  • 切片用于获取字符串的一部分,可以指定起始索引和结束索引
text = 'Python' substring = text[1:4] # 从索引1到索引4(不包括4) print(substring) # 输出: yth

[2]步长

text = 'Python' substring = text[1:4:2] # 从索引1到索引4(不包括4) 步长为 2 ,所以 索引1为 y 和 索引3 为 h print(substring) # 输出: yh

[3]反向切片

text = 'Python' substring = text[-1:-4:-2] # 从索引-1到索引-4(不包括4) 步长为 2 ,所以 索引-1为 n 和 索引-3 为 h print(substring) # 输出: nh

(3)计算长度(len)

  • len() 函数用于计算字符串的长度。
text = 'Hello, World!' length = len(text) print(length) # 输出: 13

(4)成员运算

  • innot in 用于检查一个字符串是否包含另一个字符串

[1]in

text = 'Hello, World!' contains_hello = 'Hello' in text print(contains_hello) # 输出: True

[2]not in

contains_python = 'Python' in text print(contains_python) # 输出: False

(5)去除空格(strip)

strip() 方法用于去除字符串首尾的空格。

[1] 默认 strip

  • 默认情况下,strip() 方法会去除字符串开头和结尾的所有空格。
text = ' Hello, World! ' stripped_text = text.strip() print(stripped_text) # Output: Hello, World!

[2] 左去除 lstrip

  • lstrip() 方法用于去除字符串开头的空格。
text = ' Hello, World! ' left_stripped_text = text.lstrip() print(left_stripped_text) # Output: Hello, World!

[3] 右去除 rstrip

  • rstrip() 方法用于去除字符串结尾的空格。
text = ' Hello, World! ' right_stripped_text = text.rstrip() print(right_stripped_text) # Output: Hello, World!

[4] 去除指定字符

  • 如果需要去除字符串开头和结尾的指定字符,可以传入一个字符串参数给 strip() 方法。
text = '<<Hello, World!>>' stripped_text = text.strip('<>') print(stripped_text) # Output: Hello, World!
  • 这些方法在处理用户输入、文件读取等场景中经常用到,可以有效地清理字符串的格式

(6)切分(split)

  • split() 方法用于将字符串切分成多个子字符串,并返回一个包含切分后子字符串的列表。

[1] 默认切分符

  • 如果不指定切分符,则默认使用空格作为切分符。
text = 'Hello, World!' split_result = text.split() print(split_result) # Output: ['Hello,', 'World!']

[2] 指定分隔符

  • 可以通过传递一个分隔符参数给 split() 方法来指定切分符。
text = 'apple,orange,banana' split_result = text.split(',') print(split_result) # Output: ['apple', 'orange', 'banana']
  • 在处理 CSV 格式的数据、日志文件等场景中,split() 方法非常实用,可以将字符串按照指定的分隔符拆分成各个字段。

(7)遍历字符串

  • 使用 for 循环可以遍历字符串中的每个字符
text = 'Python' for char in text: print(char) # 输出: # P # y # t # h # o # n

(8)字符串重复

  • 使用 * 运算符可以实现字符串的重复
original_str = 'ABC' repeated_str = original_str * 3 print(repeated_str) # 输出: ABCABCABC

(9)大小写转换

[1]小写转大写(upper())

  • 将给定字符串中的所有字母变为大写
text = 'hello' uppercase_text = text.upper() print(uppercase_text) # 输出: HELLO

[2]大写转小写(lower())

  • 将给定字符串中的所有字母变为小写
text = 'WORLD' lowercase_text = text.lower() print(lowercase_text) # 输出: world

(10)首尾字符判断

[1]判断字符开头(startswith())

  • startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
text = 'Python is fun' result = text.startswith('Python') print(result) # 输出: True

[2]判断字符结尾(endswith())

  • endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
text = 'Python is fun' result = text.endswith('fun') print(result) # 输出: True

(11)格式化输出

  • 之前讲到过 print() 函数的用法,这只是最简单最初级的形式,print() 还有很多高级的玩法,比如格式化输出。

[1] % 输出

  • 使用 % 运算符进行格式化输出,可以在字符串中插入占位符,然后通过 % 运算符传入相应的值。
# 格式化输出语法一 : % name = "Dream" age = 18 height = 175.5 # 使用 %s 占位符,输出字符串 print("My name is %s." % name) # My name is Dream. # 使用 %d 占位符,输出整数 print("My age is %d." % age) # My age is 18. # 使用 %f 占位符,输出浮点数,默认保留六位小数 print("My height is %f." % height) # My height is 175.500000. # 使用 %.2f 占位符,保留两位小数 print("My height is %.2f." % height) # My height is 175.50. # 使用 %x 占位符,输出十六进制整数 number = 255 print("Number in hex: %x." % number) # Number in hex: ff. # 两个以上的占位符格式化输出 print("My name is %s; My age is %d" % (name, age)) # My name is Dream; My age is 18
  • 在上例中,%s%d 是占位符,分别表示字符串和整数,而 (name, age) 是传入这两个占位符的实际值。
  • 占位符类型
    • %s:字符串
    • %d:整数
    • %f:浮点数
    • %x:十六进制整数

[2] formate 输出

  • 使用 format 方法进行格式化输出,通过花括号 {} 表示占位符,然后调用 format 方法传入实际值
name = "Dream" age = 18 # 格式化输出语法三 : formate --- 按位置放变量 print("My name is {}; My age is {}".format(name, age)) # My name is Dream; My age is 18 # 可以根据索引放变量 : 一个变量可以反复使用多次 print("My name is {1}; My age is {0}".format(age, name)) # 可以根据关键字传值 , 根据关键字传参数的时候可以不考虑位置 print("My name is {name}; My age is {age}".format(name=name, age=age))
  • 在这个例子中,{} 是占位符,它会按顺序依次填充传入 format 方法的值

[3] f + {} 输出

  • 使用 f-string(f + {})进行格式化输出,通过在字符串前加上 fF 前缀,然后在字符串中使用 {} 表示占位符,并在 {} 中直接引用变量。
name = "Dream" age = 18 # 格式化输出语法二 : f + {} print(f"My name is {name}; My age is {age}") # My name is Dream; My age is 18

(12)拼接join

  • 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
res_1 = '%'.join('hello') # 从字符串'hello'中取出多个字符串,然后按照%作为分隔符号进行拼接 print(res_1) # h%e%l%l%o res_2 = '|'.join(['Dream', '18', 'read']) # 从列表中取出多个字符串,然后按照*作为分隔符号进行拼接 print(res_2) # Dream|18|read

(13)替换replace

  • 用新的字符替换字符串中旧的字符
res_1 = 'my name is Dream, my age is 18!' # 将Dream的年龄由18岁改成73岁 res_1 = res_1.replace('18', '73') # 语法:replace('旧内容', '新内容') print(res_1) # my name is Dream, my age is 73! # 可以指定修改的个数 res_2 = 'my name is Dream, my age is 18!' res_2 = res_2.replace('my', 'MY', 1) # 只把一个my改为MY print(res_2) # MY name is Dream, my age is 18!

(14)判断类型isdigit

  • 判断字符串是否是纯数字组成,返回结果为True或False
str8 = '5201314' res_1 = str8.isdigit() print(res_1) # True str8 = '123g123' res_2 = str8.isdigit() print(res_2) # False

【4】内置方法(熟悉)

(1)查找

[1]find

  • 从指定范围内查找子字符串的起始索引,从左向右查找,找得到则返回元素所在的索引位置,找不到则返回-1
msg = 'tony say hello' # 在索引为1和2(顾头不顾尾)的字符中查找字符o的索引 res = msg.find('o', 1, 3) print(res) # 1

[2]rfind

  • 从指定范围内查找子字符串的起始索引,从右向左查找,找得到则返回元素所在的索引位置,找不到则返回-1
msg = 'tony say hello' # 在整个字符串中查找字符o的最右边的索引 res = msg.rfind('o') print(res) # 13

[3]index

  • index:同find,但在找不到时会报错
msg = 'tony say hello' # 在整个字符串中查找字符o的最左边的索引 res = msg.index('o') print(res) # 1

[4]rindex

  • index:同rfind,但在找不到时会报错
msg = 'tony say hello' # 在整个字符串中查找字符o的最右边的索引 res = msg.rindex('o') print(res) # 13

[5]count

  • 统计指定字符在大字符串中出现的次数
msg = 'tony say hello' # 统计字符串o在大字符串中出现的次数 res = msg.count('o') print(res) # 2

(2)填充

[1]center

  • 用指定字符填充指定字符串
  • 字符串长度要基于给指定字符长度的基础上增加
  • 如果两侧不平衡,则右多左少
msg = 'tony' # 用字符o将字符串居中 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 - 填充 # 如果填充长度两侧不平衡,则右多左少分配 res = msg.center(len(msg) + 6, '-') print(res) # --tony---

[2]ljust

  • 字符串长度要基于给指定字符长度的基础上增加
  • 左对齐,指定字符填充在原有字符串的右侧
msg = 'tony' # 用字符o将字符串向左对齐 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 - 填充 # 填充在原有字符串的右侧 res = msg.ljust(len(msg) + 6, '-') print(res) # tony------

[3]rjust

  • 字符串长度要基于给指定字符长度的基础上增加
  • 左对齐,指定字符填充在原有字符串的左侧
msg = 'tony' # 用字符o将字符串向右对齐 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 - 填充 # 填充在原有字符串的左侧 res = msg.rjust(len(msg) + 6, '-') print(res) # ------tony

[4]zfill

  • 字符串长度要基于给指定字符长度的基础上增加
  • 用 0 填充,填充在字符串左侧
msg = 'tony' # 右对齐 # 总长度为原有字符串长度 + 需要增加的字符长度 # 在原有字符串基础上,剩余的位置用指定字符 0 填充 # 填充在原有字符串的左侧 res = msg.zfill(len(msg) + 6) print(res) # 000000tony

(3)制表符

  • expandtabs
name = 'dream\thello' # \t表示制表符(tab键) print(name) # dream hello 默认四个字符 location = "China\tFirst" expanded_name = location.expandtabs(2) # 修改\t制表符代表的空格数 print(expanded_name) # China First

(4)首字母大写(captalize)

  • 只会将这一行的第一个单词的首字母大写,其他单词不变
text = 'hello world' capitalized_text = text.capitalize() print(capitalized_text) # 'Hello world'

(5)大小写翻转(swapcase)

  • 大写变小写,小写变大写,进行颠倒
mixed_case = 'HeLLo WoRLd' swapped_case = mixed_case.swapcase() print(swapped_case) # 'hEllO wOrlD'

(6)单词首字母大写(title)

  • 将给定句子的每一个单词的首字母大写
  • 要符合英文句子的语法规范,每个单词之间要有空格
sentence = 'the quick brown fox' title_case = sentence.title() print(title_case) # 'The Quick Brown Fox'

【5】判断字符串类型

name = 'Dream123' print(name.isalnum()) # 字符串中既可以包含数字也可以包含字母,True print(name.isalpha()) # 字符串中只包含字母,False print(name.isidentifier()) # 字符串是否是合法标识符,True print(name.islower()) # 字符串是否是纯小写,True print(name.isupper()) # 字符串是否是纯大写,False print(name.isspace()) # 字符串是否全是空格,False print(name.istitle()) # 字符串中的单词首字母是否都是大写,False

【四】列表类型(list)

【1】列表类型定义

  • 列表是Python中最常用的数据类型之一,用于存储一组有序的元素

【2】定义

  • 列表可以包含多个元素,每个元素之间用逗号 , 隔开,并用方括号 [] 括起来。
# 示例 numbers = [1, 2, 3, 4, 5] names = ['Alice', 'Bob', 'Charlie', 'David'] mixed_list = [1, 'two', 3.0, 'four', 5]

【3】内置方法(优先)

(1)类型强转

  • 但凡能被for循环遍历的数据类型都可以传给list()转换成列表类型
    • list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中
# 示例 string = 'hello' list_from_string = list(string) print(list_from_string) # 输出: ['h', 'e', 'l', 'l', 'o'] tuple_example = (1, 2, 3) list_from_tuple = list(tuple_example) print(list_from_tuple) # 输出: [1, 2, 3] range_example = range(5) list_from_range = list(range_example) print(list_from_range) # 输出: [0, 1, 2, 3, 4]

(2)按索引存取值

  • 即可存也可以取

[1]正向取值

# 示例 numbers = [1, 2, 3, 4, 5] first_number = numbers[0] print(first_number) # 输出: 1

[2]反向取值

# 示例 numbers = [1, 2, 3, 4, 5] last_number = numbers[-1] print(last_number) # 输出: 5

[3]索引取值无则报错

  • 对于list来说,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在则报错
# 示例 numbers = [1, 2, 3, 4, 5] index_10 = numbers[10] # IndexError: list index out of range print(index_10)

(3)切片

[1]顾头不顾尾

# 示例 numbers = [1, 2, 3, 4, 5] sliced_numbers = numbers[1:4] print(sliced_numbers) # 输出: [2, 3, 4]

[2]步长

# 示例 numbers = [1, 2, 3, 4, 5] stepped_numbers = numbers[0:4:2] print(stepped_numbers) # 输出: [1, 3]

(4)计算长度

# 示例 numbers = [1, 2, 3, 4, 5] length = len(numbers) print(length) # 输出: 5

(5)成员运算

[1]in

# 示例 numbers = [1, 2, 3, 4, 5] contains_3 = 3 in numbers print(contains_3) # 输出: True

[2]not in

# 示例 numbers = [1, 2, 3, 4, 5] not_contains_6 = 6 not in numbers print(not_contains_6) # 输出: True

(6)增加

[1]默认追加(append())

  • append()默认追加到末尾(不管是什么类型的数据,都会当成一个整体元素填进去)
# 示例 numbers = [1, 2, 3, 4, 5] numbers.append(6) print(numbers) # 输出: [1, 2, 3, 4, 5, 6]

[2]一次性添加多个(extend())

  • extend()一次性在列表尾部添加多个元素、合并列表
# 示例 numbers = [1, 2, 3, 4, 5] more_numbers = [6, 7, 8] numbers.extend(more_numbers) print(numbers) # 输出: [1, 2, 3, 4, 5, 6, 7, 8]

[3]指定位置添加(insert)

  • insert()在指定位置添加元素(索引位置,不管是什么类型的数据,都会当成一个整体元素填进去)
# 示例 numbers = [1, 2, 3, 4, 5] numbers.insert(1, 10) print(numbers) # 输出: [1, 10, 2, 3, 4, 5]

(7)删除

[1]del

  • 删除指定索引的元素
# 示例 numbers = [1, 2, 3, 4, 5] del numbers[2] print(numbers) # 输出: [1, 2, 4, 5]

[2]pop

  • pop()默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素
# 示例 numbers = [1, 2, 3, 4, 5] popped_value = numbers.pop(2) print(popped_value) # 输出: 3 print(numbers) # 输出: [1, 2, 4]

[3]remove

  • remove()括号内指名道姓表示要删除哪个元素,没有返回值
# 示例 numbers = [1, 2, 3, 4, 3, 5] numbers.remove(3) print(numbers) # 输出: [1, 2, 4, 3, 5]
  • 在这个例子中,remove(3) 删除了列表中的第一个值为 3 的元素。
  • 如果值不存在,会引发 ValueError 异常。
  • 这是与 pop() 不同的地方,pop() 是通过索引来删除元素的

(8)颠倒元素(reverse())

# 示例 numbers = [1, 2, 3, 4, 5] numbers.reverse() print(numbers) # 输出: [5, 4, 3, 2, 1]
  • 在这个例子中,reverse() 将列表中的元素颠倒,原来的第一个元素变成了最后一个,原来的最后一个元素变成了第一个

(9)元素排序(sort())

  • sort() 方法用于对列表进行排序,默认是升序排序。
# 示例 numbers = [5, 2, 9, 1, 7] numbers.sort() print(numbers) # 输出: [1, 2, 5, 7, 9]
  • 如果需要降序排序,可以使用 reverse 参数:
# 示例 numbers = [5, 2, 9, 1, 7] numbers.sort(reverse=True) print(numbers) # 输出: [9, 7, 5, 2, 1]
  • 需要注意的是,sort() 方法会直接修改原列表,而不会返回一个新的排序后的列表。

(10)元素排序(sorted())

  • 如果你需要保留原列表,可以使用 sorted() 函数
# 示例 numbers = [5, 2, 9, 1, 7] sorted_numbers = sorted(numbers) print(sorted_numbers) # 输出: [1, 2, 5, 7, 9] print(numbers) # 输出: [5, 2, 9, 1, 7]
  • sort() 方法默认是按照元素的大小进行排序,如果需要自定义排序规则,可以使用 key 参数,传入一个函数
  • 。例如,按照元素的绝对值进行排序:
# 示例 numbers = [-5, 2, -9, 1, 7] numbers.sort(key=abs) print(numbers) # 输出: [1, 2, -5, 7, -9]
  • key 参数指定的函数将应用于列表中的每个元素,用于提取排序的关键字。

(10)遍历循环

  • 遍历循环是对列表中的每个元素进行迭代或循环处理。常用的遍历方式有 for 循环和 while 循环。

[1]for 循环遍历列表

# 示例 fruits = ['apple', 'banana', 'orange'] for fruit in fruits: print(fruit) # 输出: # apple # banana # orange

[2]while 循环遍历列表

# 示例 fruits = ['apple', 'banana', 'orange'] index = 0 while index < len(fruits): print(fruits[index]) index += 1 # 输出: # apple # banana # orange
  • for 循环更加简洁,但 while 循环提供了更多的控制选项。
  • 通常情况下,推荐使用 for 循环遍历列表。

[3]遍历时获取索引

  • 在遍历循环中,有时需要获取元素的索引值。
  • 可以使用 enumerate() 函数实现:
# 示例 fruits = ['apple', 'banana', 'orange'] for index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") # 输出: # Index: 0, Fruit: apple # Index: 1, Fruit: banana # Index: 2, Fruit: orange

[4]遍历时获取索引和值

  • 如果需要同时获取元素的索引和值,可以使用 enumerate() 函数:
# 示例 fruits = ['apple', 'banana', 'orange'] for index, fruit in enumerate(fruits): print(f"Index: {index}, Fruit: {fruit}") # 输出: # Index: 0, Fruit: apple # Index: 1, Fruit: banana # Index: 2, Fruit: orange
  • 这样就可以在循环中同时获取元素的索引和值。

(11)步长操作

[1]正向步长

  • 正向步长是从列表的开头向末尾按指定步长取元素:
# 示例 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = numbers[::2] # 从头到尾,步长为2 print(result) # 输出: [1, 3, 5, 7, 9]

[2]反向步长

  • 反向步长是从列表的末尾向开头按指定步长取元素:
# 示例 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] result = numbers[::-2] # 从尾到头,步长为2 print(result) # 输出: [9, 7, 5, 3, 1]

[3]列表翻转

  • 列表翻转是指将列表中的元素顺序颠倒过来:
# 示例 numbers = [1, 2, 3, 4, 5] print(numbers[::-1]) # 列表翻转 # 输出: [5, 4, 3, 2, 1]
  • 这些步长操作可以在遍历列表时提供更灵活的选项,根据需求选择不同的步长值以获取所需的元素。

(补充)字符串排序

  • 我们常用的数字类型直接比较大小,但其实,字符串、列表等都可以比较大小
  • 原理相同:都是依次比较对应位置的元素的大小,如果分出大小,则无需比较下一个元素
# 对列表中的数字进行排序 l1 = [1, 2, 3] l2 = [2, ] print(l2 > l1) # 默认按数字大小进行排序 # True # 字符之间的大小取决于它们在ASCII表中的先后顺序,越往后越大 s1 = 'abc' s2 = 'az' print(s2 > s1) # s1与s2的第一个字符没有分出胜负,但第二个字符'z'>'b',所以s2>s1成立 # True # 所以我们也可以对下面这个列表排序 l = ['A', 'z', 'adjk', 'hello', 'hea'] l.sort() print(l) # ['A', 'adjk', 'hea', 'hello', 'z']
  • 当我们使用sort()方法对列表进行排序时,Python会按照以下原理进行比较和排序:

    • Python使用的是一种稳定的排序算法,通常是Timsort(合并排序和插入排序的混合算法)。

    • 对于字符串,比较的是字符的ASCII码值。在ASCII码表中,大写字母在小写字母之前,因此大写字母会排在小写字母的前面。在你提供的例子中,'A'的ASCII码小于'adjk'中的任何字符,而'z'的ASCII码大于其他所有字符。

    • 对于字符串列表,Python按照元素的字典顺序进行比较。首先比较第一个元素,如果相等则继续比较下一个元素,以此类推。

  • 在上述例子中,列表['A', 'z', 'adjk', 'hello', 'hea']会按照以下步骤排序:

    • 'A''adjk'比较,由于'A'的ASCII码小,所以 'A' 排在前面。

    • 'adjk''hea'比较,由于'adjk'的ASCII码小,所以 'adjk' 排在前面。

    • 'hea''hello'比较,由于'hea'的ASCII码小,所以 'hea' 排在前面。

    • 'hello''z'比较,由于'hello'的ASCII码小,所以 'hello' 排在前面。

    • 最后是 'z',它是最大的,所以 'z' 排在最后。

  • 最终,排序后的列表为['A', 'adjk', 'hea', 'hello', 'z']

【五】元组类型(tuple)

【1】元组类型定义

  • 元组(Tuple)是Python中的一种有序、不可变的数据类型。
  • 元组使用小括号()来定义,可以包含任意类型的元素,包括数字、字符串、列表等。

【2】定义

  • 在Python中,可以使用逗号,来创建元组,通常也建议使用小括号,尽管小括号并不是必须的。例如:
# 使用逗号 my_tuple = 1, 2, 3 # 使用小括号 my_tuple_explicit = (1, 2, 3)

【3】内置方法

(1)类型强转

  • 但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型
  • 使用tuple()函数可以将其他可迭代对象转换为元组
# 示例 numbers_list = [1, 2, 3, 4, 5] numbers_tuple = tuple(numbers_list) print(numbers_tuple) # 输出: (1, 2, 3, 4, 5)

(2)索引取值

  • 与列表类似,元组也支持按索引存取值

[1]正索引取值

# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print(fruit_tuple[1]) # 输出: banana

[2]负索引取值

# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print(fruit_tuple[-1]) # 输出: cherry

[3]只能取不能改

  • 与列表相同,如果索引不存在,会抛出IndexError
# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print(fruit_tuple[3]) # 抛出 IndexError

(3)切片(顾头不顾尾)

  • 与列表一样,元组也支持切片操作

[1]顾头不顾尾

# 示例 fruit_tuple = ('apple', 'banana', 'cherry', 'date', 'elderberry') print(fruit_tuple[1:4]) # 输出: ('banana', 'cherry', 'date')

[2]步长

# 示例 numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) print(numbers_tuple[::2]) # 输出: (1, 3, 5, 7, 9)

(4)计算长度

  • 使用len()函数可以获取元组的长度
# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print(len(fruit_tuple)) # 输出: 3

(5)成员运算

  • 与列表相同,元组也支持innot in运算符

[1]in

# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print('banana' in fruit_tuple) # 输出: True print('orange' not in fruit_tuple) # 输出: True

[2]not in

# 示例 fruit_tuple = ('apple', 'banana', 'cherry') print('orange' not in fruit_tuple) # 输出: True

(6)遍历循环

  • 使用for循环可以遍历元组中的每个元素
# 示例 fruit_tuple = ('apple', 'banana', 'cherry') for fruit in fruit_tuple: print(fruit) # 输出: # apple # banana # cherry

(7)元组拼接

  • 使用+运算符可以将两个元组拼接成一个新的元组
# 示例 tuple1 = (1, 2, 3) tuple2 = ('a', 'b', 'c') result_tuple = tuple1 + tuple2 print(result_tuple) # 输出: (1, 2, 3, 'a', 'b', 'c')

(8)元组重复

  • 使用*运算符可以将元组重复指定次数
# 示例 fruit_tuple = ('apple', 'banana', 'cherry') result_tuple = fruit_tuple * 2 print(result_tuple) # 输出: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')

【六】布尔类型(bool)

【1】强制类型转换

num = 1 # 为真的情况能转为 True print(bool(num), type(bool(num))) # True <class 'bool'> name = 'dream' # 为真的情况能转为 True print(bool(name), type(bool(name))) # True <class 'bool'> num_one = 0 # 为假的情况能转为 False print(bool(num_one), type(bool(num_one))) # False <class 'bool'> name = '' # 为假的情况能转为 False print(bool(name), type(bool(name))) # False <class 'bool'>

【2】真

  • 布尔值为 True: True 本身表示真。
  • 非零数字: 除了零之外的任何整数或浮点数都被视为真。
  • 非空字符串: 非空字符串被视为真。
  • 非空列表、非空字典、非空集合等: 如果容器类型中包含元素,被视为真。

【3】假

  • 布尔值为 False: 显而易见,False 本身就表示假。

  • 数字零: 数字类型中,整数或浮点数中的零被视为假。

  • 空字符串: 空字符串 '' 被视为假。

  • 空列表、空字典、空集合等: 对于容器类型,如果它们为空,被视为假。

【七】字典类型(dict)

【1】字典类型定义

  • 字典(Dictionary)是一种无序的数据集合,使用键(key)和值(value)之间的映射关系来存储数据。

  • 字典是Python中唯一的映射类型,其它语言中可能称为关联数组或哈希表。

  • 字典的特点:

    • 字典中的数据是无序的,不能通过索引来访问,而是通过键来访问。

    • 字典中的键必须是不可变的,通常使用字符串、数字或元组作为键。

    • 字典中的值可以是任意类型,包括数字、字符串、列表、字典等。

  • 字典的创建使用花括号 {},并使用冒号 : 分隔键和值。

  • 多个键值对之间使用逗号 , 分隔。

# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'}

【2】定义

  • 定义字典时,键和值之间使用冒号 : 分隔,多个键值对之间使用逗号 , 分隔。
  • 字典的键必须是不可变的,通常使用字符串、数字或元组作为键。
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'}
  • 在定义字典时,也可以使用 dict 函数
# 示例 person_info = dict(name='Dream', age=25, gender='male')

【3】内置方法

(1)取值

[1]按[key]取值

  • 使用中括号加键名的方式可以直接获取字典中对应键的值
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print(person_info['name']) # 输出: Dream

[2]get取值

  • 使用get方法可以根据键获取对应的值,如果键不存在,则返回指定的默认值(默认为None
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print(person_info.get('name')) # 输出: Dream print(person_info.get('height', 175)) # 输出: 175

(2)计算长度

  • 使用len函数可以计算字典中键值对的个数
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} length = len(person_info) print(length) # 输出: 3

(3)成员运算

  • 使用innot in可以判断一个键是否存在于字典中
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} print('name' in person_info) # 输出: True print('height' not in person_info) # 输出: True

(4)增加

[1]新增键值对

  • 使用update方法可以批量新增键值对,如果键已经存在,则更新对应的值
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} person_info['height'] = 175 print(person_info) # 输出: {'name': 'Dream', 'age': 25, 'gender': 'male', 'height': 175}

[2]批量新增键值对(update())

  • 使用update方法可以批量新增键值对,如果键已经存在,则更新对应的值
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} person_info.update({'height': 175, 'weight': 70}) print(person_info) # 输出: {'name': 'Dream', 'age': 25, 'gender': 'male', 'height': 175, 'weight': 70}

[3]增加值并返回值(setdefault())

  • setdefault(key, default) 方法用于获取指定键的值,如果键不存在,则返回默认值,并在字典中添加键值对。
# 示例 person_info = {'name': 'Tony', 'age': 25} # 使用setdefault()获取键值,如果键不存在,则添加新键值对 gender = person_info.setdefault('gender', 'male') print(gender) # 输出: male print(person_info) # 输出: {'name': 'Tony', 'age': 25, 'gender': 'male'}
  • 如果字典中存在键 'gender',则 setdefault() 方法返回对应的值;
  • 如果不存在,则添加新键值对 'gender': 'male' 并返回默认值 'male'

(5)删除

[1]按键删除(del())

  • 使用del关键字可以根据键删除字典中的键值对
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} del person_info['age'] print(person_info) # 输出: {'name': 'Dream', 'gender': 'male'}

[2]弹出键值对(pop())

  • 使用pop方法可以根据键弹出字典中的键值对,同时返回被弹出的值
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} popped_value = person_info.pop('age') print(popped_value) # 输出: 25 print(person_info) # 输出: {'name': 'Dream', 'gender': 'male'}

[3]清空字典(clear())

  • 使用clear方法可以清空字典中的所有键值对
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} person_info.clear() print(person_info) # 输出: {}

[4]随机删除键值对(popitem())

  • popitem() 方法用于随机删除字典中的一个键值对,并以元组的形式返回被删除的键值对。
  • 字典是无序的,所以删除的是一个随机的键值对。
# 示例 person_info = {'name': 'Tony', 'age': 25, 'gender': 'male'} # 随机删除一个键值对 removed_item = person_info.popitem() print(removed_item) # 输出: ('gender', 'male') print(person_info) # 输出: {'name': 'Tony', 'age': 25}
  • popitem() 在 Python 3.7+ 中删除的是字典中的“末尾”键值对,但在旧版本的 Python 中,删除的并不是末尾的键值对。
  • 所以在使用 popitem() 时要注意版本兼容性。

(6)键对(keys())

  • 使用keys方法可以获取字典中所有的键,返回一个可迭代的视图对象
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} keys = person_info.keys() print(keys) # 输出: dict_keys(['name', 'age', 'gender'])

(7)值对(values())

  • 使用values方法可以获取字典中所有的值,返回一个可迭代的视图对象
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} values = person_info.values() print(values) # 输出: dict_values(['Dream', 25, 'male'])

(8)键值对(items())

  • 使用items方法可以获取字典中所有的键值对,返回一个可迭代的视图对象
# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} items = person_info.items() print(items) # 输出: dict_items([('name', 'Dream'), ('age', 25), ('gender', 'male')])

(9)遍历循环

[1]只遍历key

# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for key in person_info: print(key) # 输出: # name # age # gender

[2]只遍历value

# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for value in person_info.values(): print(value) # 输出: # Dream # 25 # male

[3]遍历key和value

# 示例 person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} for key, value in person_info.items(): print(f'{key}: {value}') # 输出: # name: Dream # age: 25 # gender: male

(10)字典排序(sorted())

  • 字典的排序是通过字典的键来进行的,使用 sorted() 函数可以对字典进行排序。
# 示例 my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} # 对字典按键排序,并返回一个列表 sorted_dict = sorted(my_dict.items()) print(sorted_dict) # 输出: [('apple', 5), ('banana', 2), ('grape', 1), ('orange', 8)]
  • 在示例中,sorted() 函数对字典 my_dict 的键进行了排序,返回了一个按键排序的元组列表。
  • 如果需要按值进行排序,可以使用 key 参数指定排序的关键字:
# 示例 my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} # 对字典按值排序,并返回一个列表 sorted_dict = sorted(my_dict.items(), key=lambda x: x[1]) print(sorted_dict) # 输出: [('grape', 1), ('banana', 2), ('apple', 5), ('orange', 8)]
  • 在这个示例中,key 参数指定了按值排序,并使用了 lambda 函数提取元组中的第二个元素(值)作为排序的关键字。

【八】集合类型(set)

【1】集合类型定义

  • 集合(Set)是 Python 中的一种无序且不重复的数据类型。
  • 集合类型的定义使用大括号 {},元素之间使用逗号 , 分隔。

【2】定义

  • 集合的定义方式与示例中的方式相同,使用大括号 {} 并将元素用逗号 , 分隔。
# 示例 my_set = {1, 2, 3, 4, 5} print(my_set) # 输出: {1, 2, 3, 4, 5}
  • 无序性
print(set('dream')) # 第一次 : {'a', 'm', 'r', 'd', 'e'} # 第二次 : {'r', 'd', 'a', 'm', 'e'}
  • 去重性
print(set('dreame')) # 第一次 : {'d', 'e', 'a', 'r', 'm'} # 第二次 : {'e', 'a', 'd', 'r', 'm'}

【3】内置方法

(0)类型强转

  • 但凡能被for循环的遍历的数据类型(强调:遍历出的每一个值都必须为不可变类型)都可以传给set()转换成集合类型
# 【1】字符串类型可以强转成集合类型 name_str = 'dream' name_str_set = set(name_str) print(name_str_set, type(name_str_set)) # {'m', 'r', 'd', 'a', 'e'} <class 'set'> # 【2】字典也可以去重 , 一般我们只对字典的值去重 # 因为字典的键一般情况下都是唯一的,不需要更改 # 【2.1】默认将字典的键转换为集合 name_dict = {'name': "dream", "age": 18, "sex": 18} name_dict_set = set(name_dict) print(name_dict_set, type(name_dict_set)) # {'name', 'age', 'sex'} <class 'set'> # 【2.2】可以选择将字典的值转换为集合并去重 name_dict_values = name_dict.values() name_dict_values_set = set(name_dict_values) print(name_dict_values_set, type(name_dict_values_set)) # {18, 'dream'} <class 'set'> # 【3】列表类型是可以转成集合类型 num_list = [1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7] num_list_set = set(num_list) print(num_list_set, type(num_list_set)) # {1, 2, 3, 4, 5, 6, 7} <class 'set'> # 【4】元组类型可以转换为集合类型 num_tuple = (1, 2, 3, 4, 5, 6, 6, 6, 6, 6) num_tuple_set = set(num_tuple) print(num_tuple_set, type(num_tuple_set)) # {1, 2, 3, 4, 5, 6} <class 'set'> # 【5】布尔类型不可以 print(set(True)) # TypeError: 'bool' object is not iterable # 【6】整数类型不可以 print(set(1)) # TypeError: 'int' object is not iterable # 【7】浮点数类型不可以 print(set(1.0)) # TypeError: 'float' object is not iterable
  • 在这个示例中,my_list 是一个包含重复元素的列表,通过使用 set() 将其转换为集合,得到了一个去重后的集合 my_set

(1)添加元素

[1] 添加单个元素(add())

  • add(element) 方法用于向集合中添加单个元素。
# 示例 my_set = {1, 2, 3} my_set.add(4) print(my_set) # 输出: {1, 2, 3, 4}

[2]添加多个元素(update())

  • update(iterable) 方法用于向集合中添加多个元素,参数是一个可迭代对象。
# 示例 my_set = {1, 2, 3} my_set.update([3, 4, 5]) print(my_set) # 输出: {1, 2, 3, 4, 5}

(2)删除元素

[1] 删除指定元素(remove())

  • remove(element) 方法用于移除集合中的指定元素,如果元素不存在则会引发 KeyError。
# 示例 my_set = {1, 2, 3, 4, 5} my_set.remove(3) print(my_set) # 输出: {1, 2, 4, 5}

[2] 删除指定元素(discard())

  • discard(element) 方法用于移除集合中的指定元素,如果元素不存在则不会引发错误。
# 示例 my_set = {1, 2, 3, 4, 5} my_set.discard(3) print(my_set) # 输出: {1, 2, 4, 5}

[3] 随机删除元素(pop())

  • pop() 是基于HashMap实现的,它总是「删除」集合中的「第一个元素」,由于集合是「无序」的,所以它看起来就像是「随机」删除元素。

  • pop() 方法用于随机移除集合中的一个元素,如果集合为空则引发 KeyError。

# 示例 my_set = {1, 2, 3, 4, 5} removed_element = my_set.pop() print(removed_element) # 输出: 随机移除的元素 print(my_set) # 输出: 移除后的集合
  • 当集合中的元素是「纯数字」时,集合会按照从小到大的顺序排列元素,「最小」的数值会别排在第一个,所以pop()时,会删除最小的那个元素。
set1 = {1, 5, 3, 9, 2} print('删除前:', set1) set1.pop() print('删除后:', set1) # 删除前: {1, 2, 3, 5, 9} # 删除后: {2, 3, 5, 9} # 多执行几次,我们可以发现, pop() 每次都删除1,因为1是最小的,总是被排在第一个。
  • 当集合中的元素是「纯字符串」时,集合无法保证元素的排序,由于 pop() 总是删除第一个元素,所以这种情况看起来就是随机删除。
set1 = {'aaa', 'bbb', 'ccc', 'ddd'} print('删除前:', set1) set1.pop() print('删除后:', set1) # 第一次 : 删除了 bbb # 删除前: {'bbb', 'ddd', 'aaa', 'ccc'} # 删除后: {'ddd', 'aaa', 'ccc'} # 第二次 : 删除了 ccc # 删除前: {'ccc', 'ddd', 'bbb', 'aaa'} # 删除后: {'ddd', 'bbb', 'aaa'} # 多次执行可以发现,每次集合中的元素排序都是随机的,而 pop() 也会 “随机” 的删除集合中的第一个元素。
  • 当集合中的元素有字符串、整形、元组等「混合」组合时,元素的排序会变得随机,当然, pop() 仍然会固执地删除第一个元素。
set1 = {(1, 2), (5, 6), (9, 8), (3, 4), 'aaa', 1, 2} print('删除前:', set1) set1.pop() print('删除后:', set1) # 删除前: {1, 2, (1, 2), (3, 4), (9, 8), (5, 6), 'aaa'} # 删除后: {2, (1, 2), (3, 4), (9, 8), (5, 6), 'aaa'}
  • 使用 pop() 的集合,必须有元素,「空集合」会报错 KeyError。
  • 实际上,这并不是集合,而是字典
set1 = {} # 实际上,这并不是集合,而是字典 print(set1, type(set1)) # {} <class 'dict'> set1.pop() # TypeError: pop expected at least 1 argument, got 0

(3)集合操作

[1] 并集(union())

  • union(*others) 方法返回当前集合与其他集合的并集。
# 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} union_set = set1.union(set2) print(union_set) # 输出: {1, 2, 3, 4, 5}

[2] 交集(intersection())

  • intersection(*others) 方法返回当前集合与其他集合的交集。
# 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} intersection_set = set1.intersection(set2) print(intersection_set) # 输出: {3}

[3] 差集(difference())

  • difference(*others) 方法返回当前集合与其他集合的差集。
# 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} difference_set = set1.difference(set2) print(difference_set) # 输出: {1, 2}

[4] 对称差集(symmetric_difference())

  • symmetric_difference(other) 方法返回当前集合与其他集合的对称差集。
# 示例 set1 = {1, 2, 3} set2 = {3, 4, 5} symmetric_difference_set = set1.symmetric_difference(set2) print(symmetric_difference_set) # 输出: {1, 2, 4, 5}

[5]父集

set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断 set1 是否是 set2 的父集 is_superset = set1.issuperset(set2) print(is_superset) # 输出: True

[6]子集

set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断 set2 是否是 set1 的子集 is_subset = set2.issubset(set1) print(is_subset) # 输出: True

[7]判断(==)

set1 = {1, 2, 3, 4, 5} set2 = {2, 4} # 判断两个集合是否相等 is_equal = set1 == set2 print(is_equal) # 输出: False

(4)去重

  • 只能针对不可变类型

  • 集合本身是无序的,去重之后无法保留原来的顺序

l_old = ['a', 'b', 1, 'a', 'a'] s = set(l_old) # 将列表转成了集合 print(s) # {'b', 'a', 1} l_new = list(s) # 再将集合转回列表 print(l_new) # 去除了重复,但是打乱了顺序 # ['b', 'a', 1] # 针对不可变类型,并且保证顺序则需要我们自己写代码实现,例如 l_second = [ {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'jack', 'age': 73, 'sex': 'male'}, {'name': 'tom', 'age': 20, 'sex': 'female'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'lili', 'age': 18, 'sex': 'male'}, ] new_l_second = [] for dic in l_second: if dic not in new_l_second: new_l_second.append(dic) print(new_l_second) # 结果:既去除了重复,又保证了顺序,而且是针对不可变类型的去重 ''' [ {'name': 'lili', 'age': 18, 'sex': 'male'}, {'name': 'jack', 'age': 73, 'sex': 'male'}, {'name': 'tom', 'age': 20, 'sex': 'female'} ] '''

(5)计算长度(len())

# 计算集合长度 length = len(unique_set) print(length) # 输出: 5

(6)遍历循环

my_set = {1, 2, 3, 'a', 'b'} # 遍历集合 for item in my_set: print(item) # 输出: 1 2 3 'a' 'b'

(7)成员运算

[1]in

is_in_set = 'a' in my_set print(is_in_set) # 输出: True

[2]not in

is_not_in_set = 6 not in my_set print(is_not_in_set) # 输出: True

【八】数据类型总结

按存值个数区分
只能存一个值:可称为标量/原子类型 数字类型、字符串
可以存放多个值:可称为容器类型 列表、元祖、字典
按照访问方式区分
直接访问:只能通过变量名访问整个值 数字类型
顺序访问:可以通过索引访问指定的值,索引代表顺序,又称为序列类型 字符串、列表、元祖
key访问:可以用key访问指定的值,又称为映射类型 字典
按可变不可变区分
可变类型 列表、字典
不可变类型 数字、字符串、元祖

__EOF__

本文作者Chimengmeng
本文链接https://www.cnblogs.com/dream-ze/p/17840566.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @ 2023-11-18 15:14  Chimengmeng  阅读(352)  评论(0编辑  收藏  举报