Loading

数据类型的内置方法

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

  • 数据类型是用来记录事物状态的,而事物的状态是不断变化的(如:一个人年龄的增长(操作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指定是否考虑整数的符号。
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 = "1234"
num = int(s)  # 转换成功
print(num)  # 输出:1234

s = "123a"
num = int(s)  # 会引发 ValueError

s = "123 456"
num = int(s)  # 会引发 ValueError

s = "123$"
num = int(s)  # 会引发 ValueError

(5)进制转换

  • 在Python中,整数类型提供了一些方法来进行进制转换,主要涉及到二进制、八进制、十六进制。
[1]十进制转二进制:bin()
  • 将整数转换为二进制表示,返回一个字符串。
number = 10
binary_str = bin(number)
print(binary_str)  # 输出: '0b1010'
[2]十进制转八进制:oct()
  • 将整数转换为八进制表示,返回一个字符串。
number = 10
octal_str = oct(number)
print(octal_str)  # 输出: '0o12'
[3]十进制转十六进制:hex()
  • 将整数转换为十六进制表示,返回一个字符串。
number = 10
hex_str = hex(number)
print(hex_str)  # 输出: '0xa'
#从其他进制字符串转回整数的示例:
binary_str = '0b1010'
octal_str = '0o12'
hex_str = '0xa'

print(int(binary_str, 2))  # 从二进制转回整数: 10
print(int(octal_str, 8))   # 从八进制转回整数: 10
print(int(hex_str, 16))    # 从十六进制转回整数: 10
[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() 函数将浮点数转换为整数。
  • 在Python中,你可以使用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 用于检查一个字符串是否包含另一个字符串
text = 'Green Python King!'
bool_text = 'Green' in text
bool_text_two = 'Green' not in text
print(bool_text) # True	
print(bool_text_two) # 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 = 'Green'
print(text.upper())  # GREEN
print(text.lower())  # green

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

  • 将给定字符串中的所有字母变为小写
text = 'Green'
print(text.upper())  # GREEN
print(text.lower())  # green

(10)首尾字符判断

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

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

res_1 = text.endswith('good')  # True

print(res)
print(res_1)

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

  • endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
text = 'Python is good'
res = text.startswith('Py')  # True

res_1 = text.endswith('good')  # True

print(res)
print(res_1)

(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

  • 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
name = 'Green'
res_1 = 'nb'.join(name)
print(res_1)
name_list = ['Green', 'Hqq', 'Vincent']
res_2 = 'nb|'.join(name_list)
print(res_2)
"""
Gnbrnbenbenbn
Greennb|Hqqnb|Vincent

"""

(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 = 'green say hello'

# 在索引为1和2(顾头不顾尾)的字符中查找字符o的索引
res = msg.find('n', 1, 3)
print(res) # 1

[2]rfind

  • 从指定范围内查找子字符串的起始索引,从右向左查找,找得到则返回元素所在的索引位置,找不到则返回-1
msg = 'green say hello'

# 会找到最后一个的e的索引位置
res = msg.rfind('e')
print(res) # 11

[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循环一样遍历出数据类型中包含的每一个元素然后放到列表中
# 将字符串转换为列表
s = 'hello'
list_s = list(s)

# 打印结果
print(list_s)

(2)按索引存取值

  • 即可存也可以取
# 假设我们有一个列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 取第三个元素(记得索引是从0开始的)
print(my_list[2])  # 输出 'c'

# 继续使用上面的列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 修改第三个元素为 'z'
my_list[2] = 'z'

# 打印修改后的列表
print(my_list)  # 输出 ['a', 'b', 'z', 'd', 'e']

[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来说,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在则报错
# 一个包含三个元素的列表
my_list = ['a', 'b', 'c']

# 尝试访问不存在的索引
try:
    print(my_list[3])  # 不存在的索引
except IndexError as e:
    print("Error:", e)  # 打印错误消息

(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]
numbers.append(4)  # 追加数值4
print(numbers)  # 输出: [1, 2, 3, 4]

words = ['hello', 'world']
words.append('Python')  # 追加字符串'Python'
print(words)  # 输出: ['hello', 'world', 'Python']

lists = [1, 2, 3]
lists.append([4, 5])  # 追加列表[4, 5]
print(lists)  # 输出: [1, 2, 3, [4, 5]]

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

  • extend()一次性在列表尾部添加多个元素、合并列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]

# 使用extend()方法合并list2到list1
list1.extend(list2)

# 输出结果
print(list1)  # [1, 2, 3, 4, 5, 6]
-------------------------------------------------------------
char_list = ['a', 'b', 'c']
string = "def"

# 使用extend()方法添加字符串中的每个字符
char_list.extend(string)

# 输出结果
print(char_list)  # ['a', 'b', 'c', 'd', 'e', 'f']
-------------------------------------------------------------
  • 由于遍历字典是只会遍历字典的键值,所以添加字典只会添加键值
my_list = [1, 2, 3]
my_dict = {'a': 1, 'b': 2, 'c': 3}

# 使用extend()方法添加字典
my_list.extend(my_dict)

# 输出结果
print(my_list)  # 输出 [1, 2, 3, 'a', 'b', 'c']

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

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

(7)删除

【1】del

  • 删除指定索引的元素
# 定义一个初始列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 假设我们想删除索引为2的元素,即元素'c'
del my_list[2]

# 输出结果看看列表现在的内容
print(my_list)  # 输出 ['a', 'b', 'd', 'e']
  • 删除一个切片
# 再次定义一个初始列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 假设我们想删除索引1到3(不包括3)的元素
del my_list[1:3]

# 输出结果看看列表现在的内容
print(my_list)  # 输出 ['a', 'd', 'e']

【2】pop

  • pop()默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素
  • 当不传递任何参数时,pop() 会删除并返回列表的最后一个元素
# 定义一个初始列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 使用pop()默认删除并返回最后一个元素
removed_element = my_list.pop()

# 输出结果
print("Removed Element:", removed_element)  # 输出: Removed Element: e
print("List after pop:", my_list)  # 输出: List after pop: ['a', 'b', 'c', 'd']
  • 也可以通过传递索引给 pop() 来删除特定位置的元素:
# 定义一个初始列表
my_list = ['a', 'b', 'c', 'd', 'e']

# 使用pop(2)删除索引为2的元素
removed_element = my_list.pop(2)  # 删除并返回索引为2的元素

# 输出结果
print("Removed Element:", removed_element)  # 输出: Removed Element: c
print("List after pop:", my_list)  # 输出: List after pop: ['a', 'b', 'd', 'e']

【3】remove

  • remove()括号内指名道姓表示要删除哪个元素,没有返回值
# 定义一个初始列表
my_list = ['a', 'b', 'c', 'd', 'b', 'e']

# 使用remove()删除元素'b',它将删除第一个出现的'b'
my_list.remove('b')

# 输出结果看看列表现在的内容
print(my_list)  # 输出: ['a', 'c', 'd', 'b', 'e']

(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
print(my_tuple)  # 输出: (1, 2)

# 创建相同元素的元组,但使用小括号
my_tuple = (1, 2)
print(my_tuple)  # 输出: (1, 2)

# 单个元素的元组
single_element_tuple = (1,)
print(type(single_element_tuple))  # 输出: <class 'tuple'>

#如果你省略了逗号。not_a_tuple 就不是元组,而是普通的整数。
not_a_tuple = (1)
print(type(not_a_tuple))  # 输出: <class 'int'>

【3】内置方法

(1)类型强转

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

print(my_tuple)  # 输出: (1, 2, 3, 4, 5)

# 将字符串转换为元组
my_string = "hello"
my_tuple = tuple(my_string)

print(my_tuple)  # 输出: ('h', 'e', 'l', 'l', 'o')

# 将字典的键转换为元组
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_tuple = tuple(my_dict)  # 取字典的键

print(my_tuple)  # 输出: ('a', 'b', 'c')

(2)索引取值

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

【1】正索引取值

# 创建一个元组
my_tuple = ('a', 'b', 'c', 'd', 'e')

# 访问元组的第一个元素
print(my_tuple[0])  # 输出: 'a'

# 访问元组的最后一个元素
print(my_tuple[-1])  # 输出: 'e'

# 访问元组中间的元素
print(my_tuple[2])  # 输出: 'c'
  • 正如你所看到的,索引取值操作对元组来说非常直接和自然,几乎和列表一模一样。唯一的区别在于元组是不可变的,这意味着你不能通过索引来修改元组中的元素。例如,尝试执行 my_tuple[0] = 'z' 将会导致一个TypeError,因为元组不支持项赋值。

【2】负索引取值

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

【3】只能取不能改

  • 与列表相同,如果索引不存在,会抛出TypeError
my_tuple = (1, 2, 3)
try:
    my_tuple[0] = 'a'  # 尝试修改元组
except TypeError as e:
    print("Error:", e)  # 输出错误信息

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

  • 在Python中同样支持切片操作,其工作方式与列表(list)的切片操作完全一致。

[1]顾头不顾尾

my_tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

# 获取索引2到索引5(不包括5)的元素
print(my_tuple[2:5])  # 输出: (2, 3, 4)

# 获取从开始到索引5的元素
print(my_tuple[:5])  # 输出: (0, 1, 2, 3, 4)

# 获取从索引5到结束的元素
print(my_tuple[5:])  # 输出: (5, 6, 7, 8, 9)

# 使用负索引获取最后三个元素
print(my_tuple[-3:])  # 输出: (7, 8, 9)

# 每两个元素取一个,从头到尾
print(my_tuple[::2])  # 输出: (0, 2, 4, 6, 8)

print(my_tuple[::-1])  # 输出: (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

[2]步长

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

(4)计算长度

  • 使用len()函数可以获取元组的长度
my_tuple = (1, 2, 3, 4, 5)
# 获取元组的长度
length = len(my_tuple)

# 输出结果
print(length)  # 输出: 5

(5)成员运算

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

[1]in

my_tuple = ('a', 'b', 'c', 'd', 'e')

# 检查 'c' 是否在元组中
print('c' in my_tuple)  # 输出: True

# 检查 'z' 是否在元组中
print('z' in my_tuple)  # 输出: False

[2]not in

# 检查 'c' 是否不在元组中
print('c' not in my_tuple)  # 输出: False

# 检查 'z' 是否不在元组中
print('z' not in my_tuple)  # 输出: True

(6)遍历循环

  • 使用for循环可以遍历元组中的每个元素
my_tuple = (1, 2, 3, 4, 5)

# 遍历元组
for item in my_tuple:
    print(item)
# 输出
1
2
3
4
5

(7)元组拼接

  • 使用+运算符可以将两个元组拼接成一个新的元组
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

# 拼接元组
combined_tuple = tuple1 + tuple2

# 输出结果
print(combined_tuple)  # 输出: (1, 2, 3, 4, 5, 6)

(8)元组重复

  • 使用*运算符可以将元组重复指定次数
my_tuple = (1, 2, 3)
# 重复元组三次
repeated_tuple = my_tuple * 3

# 输出结果
print(repeated_tuple)  # 输出: (1, 2, 3, 1, 2, 3, 1, 2, 3)

【六】布尔类型(bool)

【1】强制类型转换

# 数值类型
print(bool(0))     # False
print(bool(1))     # True
print(bool(-1))    # True

# 容器类型
print(bool([]))    # False, 空列表
print(bool([1,2])) # True, 非空列表
print(bool(""))    # False, 空字符串
print(bool("Python")) # True, 非空字符串

# None类型
print(bool(None))  # False

【2】真

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

【3】假

  • 布尔值为 False: 显而易见,False 本身就表示假。
  • 数字零: 数字类型中,整数或浮点数中的零被视为假。
  • 空字符串: 空字符串 '' 被视为假。
  • 空列表、空字典、空集合等: 对于容器类型,如果它们为空,被视为假。

【七】字典类型(dict)

【1】字典类型定义

  • 字典(Dictionary)是一种无序的数据集合,使用键(key)和值(value)之间的映射关系来存储数据。
  • 字典是Python中唯一的映射类型,其它语言中可能称为关联数组或哈希表。
  • 字典的特点:
    • 字典中的数据是无序的,不能通过索引来访问,而是通过键来访问。
    • 字典中的键必须是不可变的,通常使用字符串、数字或元组作为键。
    • 字典中的值可以是任意类型,包括数字、字符串、列表、字典等。
  • 字典的创建使用花括号 {},并使用冒号 : 分隔键和值。
  • 多个键值对之间使用逗号 , 分隔。
my_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
}

【2】定义

  • 定义字典时,键和值之间使用冒号 : 分隔,多个键值对之间使用逗号 , 分隔。
  • 字典的键必须是不可变的,通常使用字符串、数字或元组作为键。
my_dict = {
    'key1': 'value1',
    'key2': 'value2',
    'key3': 'value3'
}}
  • 在定义字典时,也可以使用 dict 函数
my_dict = dict(key1='value1', key2='value2', key3='value3')
print(my_dict)
# 输出: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

【3】内置方法

(1)取值

[1]按[key]取值

  • 使用中括号加键名的方式可以直接获取字典中对应键的值
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
print(green_info['name'])  # 输出: Green
print(green_info['age'])  # 输出: 22
print(green_info['hobby'])  # 输出: python

[2]get取值

  • 使用get方法可以根据键获取对应的值,如果键不存在,则返回指定的默认值(默认为None
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
# 获取存在的键
hobby = green_info.get('hobby')
print(hobby)  # 输出: python

# 尝试获取不存在的键,返回默认值
favorite_color = green_info.get('favorite_color', 'Not Specified')
print(favorite_color)  # 输出: Not Specified

(2)计算长度

  • 使用len函数可以计算字典中键值对的个数
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
# 计算字典中键值对的数量
count = len(green_info)

# 输出结果
print(count)  # 输出: 3

(3)成员运算

  • 使用innot in可以判断一个键是否存在于字典中
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
# 检查 'name' 是否是字典的键
is_name_key = 'name' in green_info
print(is_name_key)  # 输出: True

# 检查 'gender' 是否是字典的键
is_gender_key = 'gender' in green_info
print(is_gender_key)  # 输出: False
-------------------------------------------------------------
# 检查 'age' 是否不在字典中
is_age_not_key = 'age' not in green_info
print(is_age_not_key)  # 输出: False

# 检查 'birthday' 是否不在字典中
is_birthday_not_key = 'birthday' not in green_info
print(is_birthday_not_key)  # 输出: True

(4)增加

[1]新增键值对

  • 使用update方法可以批量新增键值对,如果键已经存在,则更新对应的值
# 更新已存在的键 'age' 和 'hobby'
green_info.update(age=23, hobby='coding')
print(green_info)  # 输出: {'name': 'Green', 'age': 23, 'hobby': 'coding'}

# 新增键值对 'gender' 和 'favorite_color'
green_info.update(gender='Not Specified', favorite_color='Blue')
print(green_info)
# 输出: {'name': 'Green', 'age': 23, 'hobby': 'coding', 'gender': 'Not Specified', 'favorite_color': 'Blue'}

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

  • 使用update方法可以批量新增键值对,如果键已经存在,则更新对应的值
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
# 新的信息
new_info = {
    'age': 23,  # 更新已有键
    'favorite_color': 'Blue'  # 新增键
}

# 使用update()方法更新字典
green_info.update(new_info)

# 输出更新后的字典
print(green_info)
# 使用由元组构成的列表更新
green_info.update([('city', 'New York'), ('gender', 'Not Specified')])

# 输出更新后的字典
print(green_info)

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

  • setdefault(key, default) 方法用于获取指定键的值,如果键不存在,则返回默认值,并在字典中添加键值对。

  • 假设我们有一个初始字典:

green_info = {
    'name': 'Green',
    'age': 22
}
  • 使用 setdefault() 获取存在的键值:
# 获取存在的键 'name' 的值
name = green_info.setdefault('name', 'Unknown')
print(name)  # 输出: Green
  • 在这个例子中,因为 'name' 键已存在于 green_info 字典中,setdefault() 方法返回了 'Green',字典没有发生改变。

  • 使用 setdefault() 添加不存在的键值对:

# 尝试获取不存在的键 'hobby' 的值,同时为其提供默认值 'None'
hobby = green_info.setdefault('hobby', 'python')
print(hobby)  # 输出: python
print(green_info)  # 输出: {'name': 'Green', 'age': 22, 'hobby': 'python'}
  • # 尝试获取不存在的键 'hobby' 的值,同时为其提供默认值 'None' hobby = green_info.setdefault('hobby', 'python') print(hobby) # 输出: python print(green_info) # 输出:

(5)删除

  • 当用于字典时,del 可以删除指定键的键值对。如果键存在于字典中,对应的键值对会被删除;如果键不存在,则会抛出 KeyError
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}

# 删除键 'hobby'
del green_info['hobby']

# 输出结果看看字典现在的内容
print(green_info)  # 输出: {'name': 'Green', 'age': 22}

try:
    # 尝试删除不存在的键 'favorite_color'
    del green_info['favorite_color']
except KeyError as e:
    print("Error:", e)  # 输出错误信息
# 如果尝试删除一个不存在的键,Python将会抛出 KeyError。

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

  • 使用pop方法可以根据键弹出字典中的键值对,同时返回被弹出的值
green_info = {
    'name': 'Green',
    'age': 22,
    'hobby': 'python'
}
# 弹出键 'hobby' 并获取对应的值
hobby = green_info.pop('hobby')
print(hobby)  # 输出: python
print(green_info)  # 输出: {'name': 'Green', 'age': 22}

# 尝试弹出不存在的键 'favorite_color' 并提供默认值
favorite_color = green_info.pop('favorite_color', 'Not Specified')
print(favorite_color)  # 输出: Not Specified

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

  • 使用clear方法可以清空字典中的所有键值对
my_dict = {'name': 'Green', 'gender': 'Male', 'hobby': 'Python', 'age': 22}
my_dict.clear()  # 这将移除my_dict中的所有条目
print(my_dict)  # 这将打印出{}

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

  • popitem() 方法用于随机删除字典中的一个键值对,并以元组的形式返回被删除的键值对。
  • 字典是无序的,所以删除的是一个随机的键值对。
my_dict = {'name': 'Green', 'gender': 'Male', 'hobby': 'Python', 'age': 22}

# 随机或者说最后插入的键值对将被删除
item = my_dict.popitem()
print(item)  # 打印被删除的键值对
print(my_dict)
# ('age', 22)
# {'name': 'Green', 'gender': 'Male', 'hobby': 'Python'}
  • popitem() 在 Python 3.7+ 中删除的是字典中的“末尾”键值对,但在旧版本的 Python 中,删除的并不是末尾的键值对。
  • 所以在使用 popitem() 时要注意版本兼容性。

(6)键对(keys())

  • 使用keys方法可以获取字典中所有的键,返回一个可迭代的视图对象
my_dict = {'name': 'Green', 'gender': 'Male', 'hobby': 'Python', 'age': 22}

keys = my_dict.keys()  # 获取所有键

# 打印所有的键
for key in keys:
    print(key)

(7)值对(values())

  • 使用values方法可以获取字典中所有的值,返回一个可迭代的视图对象
my_dict = {'name': 'Green', 'gender': 'Male', 'hobby': 'Python', 'age': 22}

values = my_dict.values()  # 获取所有值

# 打印所有的值
for value in values:
    print(value)

# 打印结果示例(具体顺序可能会有所不同):
# Green
# Male
# Python
# 22

(8)键值对(items())

  • items()方法用于获取字典中所有的键值对。它返回一个视图对象,其中包含字典的键值对。每个键值对都是一个元组,第一个元素是键,第二个元素是对应的值。
my_dict = {'name': 'Green', 'gender': 'Male', 'hobby': 'Python', 'age': 22}

items = my_dict.items()  # 获取所有键值对

# 打印所有的键值对
for key, value in items:
    print(key, value)

# 打印结果示例(具体顺序可能会有所不同):
# name Green
# gender Male
# hobby Python
# age 22

【八】集合类型(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访问指定的值,又称为映射类型 字典
按可变不可变区分
可变类型 列表、字典
不可变类型 数字、字符串、元祖
posted @ 2024-01-13 23:06  HuangQiaoqi  阅读(2)  评论(0编辑  收藏  举报