常用方法概览
| |
| int():类型强转 |
| bin():转换二进制 |
| hex():转换十六进制 |
| oct():转换八进制 |
| int(num,2/8/16) |
| |
| |
| .isdigit():判断是否均为整数数字[允许汉语数字] |
| .isdecimal():判断是否均为十进制数字[除数字外所有字符均不可以] |
| .isnumeric():对于数字的判断更宽泛,可汉语数字和整数数字同时出现 |
| |
| |
| .strip():去除空格 |
| .split()/.rsplit():切分/从右向左切分,可以传切分次数的参数 |
| .upper():全部大写 |
| .lower():全部小写 |
| .startswith():判断开头内容是否符合,返沪布尔值 |
| .endswith():判断结尾内容是否符合,返沪布尔值 |
| .join():拼接 |
| .replace(old,new):替换 |
| {}+.format():格式化输出 |
| .find():查找,返回索引值 |
| .index():同find,但找不到索引会报错 |
| .count():计数 |
| .center(长度,'填充字符'):居中对齐并按长度填充字符 |
| .ljust(长度,'填充字符')/.rjust():左/右对齐并按长度填充字符 |
| .captalize():首字母大写[仅第一个单词] |
| .swapcase():大小写反转 |
| .title():所有单词首字母大写 |
| .isidentifier():判断字符串内容是否都是合法字符 |
| |
| .append():增加一个 |
| .extend():增加多个元素 |
| .insert([索引], ):根据索引增加 |
| .del([索引]):删除索引对应的值 |
| .pop():弹出最后一个元素,可以用变量接收 |
| .remove(值):删除指定的值 |
| .sort(reverse=True/False):默认升序排序,可以传入参数reverse进行降序排序,修改后无参数返回,直接修改原值 |
| .sorted():与sort功能一致,但有返回值,可以使用变量接收 |
| .reverse():颠倒顺序 |
| |
| .update():增加键值对 |
| .setdefault(key,value):寻找键并返回键对应值,没有键就新增键值对 |
| .del():根据键值删除 |
| .pop():弹出键值对,返回值 |
| .clear():清空字典 |
| .keys():取出键对 |
| .values():取出值对 |
| .items():取出键值对 |
| .sorted():字典排序,根据ASKII码表排序 |
| |
| .add():添加单个元素 |
| .update():添加多个元素 |
| .remove():删除指定元素 |
| .discard():删除指定元素,找不到不会报错 |
| .pop():随机删除元素,数字除外[因为按照hash排列] |
| | / .union():并集 |
| - / .intersection():差集 |
| ^ / .symetric_difference():对称差集 |
【一】数字类型
【1】整数类型(int)
(1)基本运算
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__add__(num2) |
| print(result) |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__sub__(num2) |
| print(result) |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__mul__(num2) |
| print(result) |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__truediv__(num2) |
| print(result) |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__floordiv__(num2) |
| print(result) |
| |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__mod__(num2) |
| print(result) |
| |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__pow__(num2) |
| print(result) |
| |
| num1 = 5 |
| num2 = 2 |
| result = num1.__pow__(num2, 4) |
| print(result) |
| |
(2)类型强转
| |
| |
| txt = '123' |
| print(type(txt)) |
| print(type(int(txt))) |
| |
| txt2 = '123abc' |
| print(int(txt2)) |
(3)进制转换
2、二进制转换(不常用)
- 返回整数的二进制表示中最高位的位数,不包括符号和前导零。
| num = 42 |
| bit_length = num.bit_length() |
| print(bit_length) |
| |
| int.to_bytes(length, byteorder, signed) |
| num = 42 |
| byte_array = num.to_bytes(2, byteorder='big', signed=False) |
| print(byte_array) |
| |
| int.from_bytes(bytes, byteorder, signed) |
| byte_array = b'\x00*' |
| num = int.from_bytes(byte_array, byteorder='big', signed=False) |
| print(num) |
| |
1、各进制转换(更常用一些)
- 十进制转二进制
- 二进制最小位数为8位,不够补‘0’

- 二进制转十进制
[1]十进制转二进制:bin()
| num = 42 |
| binary_representation = bin(num) |
| print(binary_representation) |
| |
[2]十进制转八进制:oct()
| num = 42 |
| octal_representation = oct(num) |
| print(octal_representation) |
| |
[3]十进制转十六进制:hex()
-
将整数转换为十六进制表示,返回一个字符串。
-
十六进制中(由0~9加上a,b,c,d,e,f表示)
-
因为不可以由两位数表示,故用字母代替
- a == 10 ; b == 11 ; c == 12 ; d ==13 ; e ==14 ;f ==15
| num = 42 |
| hexadecimal_representation = hex(num) |
| print(hexadecimal_representation) |
| |
[4]其它进制转十进制:int()
| binary_str = '0b101010' |
| decimal_num = int(binary_str, 2) |
| print(decimal_num) |
| |
| |
| octal_str = '0o52' |
| decimal_num = int(octal_str, 8) |
| print(decimal_num) |
| |
| |
| hexadecimal_str = '0x2a' |
| decimal_num = int(hexadecimal_str, 16) |
| print(decimal_num) |
| |
【2】浮点数类型(float)
(1)基本运算
| |
| result_add = 3.14 + 2.5 |
| print(result_add) |
| |
| result_subtract = 5.7 - 1.2 |
| print(result_add) |
| |
| result_multiply = 2.0 * 3.5 |
| print(result_subtract) |
| |
| result_divide = 8.0 / 4.0 |
| print(result_divide) |
| |
| rounded_number = round(3.14159) |
| print(rounded_number) |
(2)类型强转
| |
| |
| txt = 123 |
| print(type(txt)) |
| print(type(float(txt))) |
| |
| txt2 = '123a' |
| print(float(txt2)) |
| |
【3】判断数字类型
(1)数字类型说明
| num1 = b'4' |
| num2 = '4' |
| num3 = '四' |
| num4 = 'Ⅳ' |
(2)判断数字类型(isdigit)
isdigit()
方法是 Python 字符串对象的方法之一,用于检查字符串是否只包含数字字符。这方法返回 True
如果字符串中所有的字符都是数字字符(0-9),否则返回 False
。
以下是 isdigit()
方法的基本用法:
| string = "12345" |
| result = string.isdigit() |
| print(result) |
| |
在这个例子中,isdigit()
方法返回 True
,因为字符串 "12345" 中只包含数字字符。
与 isdecimal()
方法不同,isdigit()
允许字符串中包含 Unicode 中的数字字符(如罗马字符),但不允许字符串中包含其他非数字字符,如空格或小数点。
| unicode_string = "一二三四五" |
| result = unicode_string.isdigit() |
| print(result) |
| |
| |
| mixed_string = "123 45" |
| result = mixed_string.isdigit() |
| print(result) |
| |
在这个例子中,isdigit()
对于包含汉字数字的字符串返回 True
,但对于包含空格的字符串返回 False
。
(3)判断小数类型(isdecimal)
isdecimal()
方法是 Python 字符串对象的方法之一,用于检查字符串是否只包含十进制数字字符。这意味着字符串中的每个字符都必须是 0 到 9 的数字字符,而不能包含小数点、负号、空格或其他非数字字符。
以下是 isdecimal()
方法的基本用法:
| string = "12345" |
| result = string.isdecimal() |
| print(result) |
| |
在这个例子中,isdecimal()
方法返回 True
,因为字符串 "12345" 中只包含十进制数字字符。
然而,需要注意的是,如果字符串包含除了数字字符以外的其他字符,isdecimal()
将返回 False
。例如:
| string = "123.45" |
| result = string.isdecimal() |
| print(result) |
| |
在这个例子中,由于字符串包含小数点,isdecimal()
返回 False
。如果你希望检查字符串中是否只包含数字字符,而不考虑小数点,可以使用 isdigit()
方法。
(4)判断数字类型(isnumeric)
isnumeric()
方法是 Python 字符串对象的方法之一,用于检查字符串是否只包含数字字符。类似于 isdigit()
方法,但 isnumeric()
还允许字符串中包含其他数字字符,如Unicode 中的数字字符(汉字数字等)。
以下是 isnumeric()
方法的基本用法:
| string = "12345" |
| result = string.isnumeric() |
| print(result) |
| |
在这个例子中,isnumeric()
方法返回 True
,因为字符串 "12345" 中只包含数字字符。
与 isdigit()
方法相比,isnumeric()
更宽泛,它允许字符串中包含 Unicode 中的其他数字字符。例如:
| unicode_string = "一二三四五" |
| result = unicode_string.isnumeric() |
| print(result) |
| |
在这个例子中,isnumeric()
对于包含汉字数字的字符串返回 True
。
需要注意的是,isnumeric()
和 isdigit()
的行为在处理不同类型的数字字符时可能有所不同,具体取决于字符串中包含的字符。在使用时,选择适合你需求的方法。
(5)无法判断浮点数
| |
| num5 = '4.3' |
| print(num5.isdigit()) |
| print(num5.isdecimal()) |
| print(num5.isnumeric()) |
【二】字符串类型(str)
【0】字符串强转
| print(str([1, 2, 3])[0]) |
| print(str({1, 2, 3})[0]) |
| print(str((1, 2, 3))[0]) |
| print(str({'a': 1})[0]) |
【1】内置方法(优先)
(0)字符串拼接(+)
| str1 = 'Hello,' |
| str2 = 'World!' |
| result_str = str1 + ' ' + str2 |
| print(result_str) |
| |
(1)索引取值
[1]正索引取值
- 字符串中的每个字符都有一个索引,正索引从左到右依次增加
| text = 'Python' |
| first_char = text[0] |
| print(first_char) |
| |
[2]反索引取值
- 反索引从右到左依次增加,最右边的字符索引为 -1。
| text = 'Python' |
| last_char = text[-1] |
| print(last_char) |
| |
[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] |
| print(substring) |
| |
[2]步长
| text = 'Python' |
| substring = text[1:4:2] |
| print(substring) |
| |
[3]反向切片
| text = 'Python' |
| substring = text[-1:-4:-2] |
| |
| |
| print(substring) |
| |
| print(text(::-1)) |
| |
(3)计算长度(len())
| text = 'Hello, World!' |
| length = len(text) |
| print(length) |
| |
(4)成员运算(in/not in)
in
和 not in
用于检查一个字符串是否包含另一个字符串
[1]in
| text = 'Hello, World!' |
| contains_hello = 'Hello' in text |
| print(contains_hello) |
| |
[2]not in
| contains_python = 'Python' in text |
| print(contains_python) |
| |
(5)去除空格(.strip())
strip()
方法用于去除字符串首尾的空格。
[1] 默认 strip
-
默认情况下,strip()
方法会去除字符串开头和结尾的所有空格。
-
| text = ' Hello, World! ' |
| stripped_text = text.strip() |
| print(stripped_text) |
| |
[2] 左去除 lstrip
[3] 右去除 rstrip
| text = ' Hello, World! ' |
| right_stripped_text = text.rstrip() |
| print(right_stripped_text) |
| |
[4] 去除指定字符
- 如果需要去除字符串开头和结尾的指定字符,可以传入一个字符串参数给
strip()
方法。
| text = '<<Hello, World!>>' |
| stripped_text = text.strip('<>') |
| print(stripped_text) |
| |
| |
| text = '<@#$%^&*<!Hello, World!>>><!@#$%^&*' |
| print(text.strip('><!@#$%^&*')) |
| |
| |
| text = 'aHello, Worlda!aaaabbbccc' |
| print(text.strip('abc')) |
| |
-
总结:
s.strip(chars)使用规则:
首先遍历chars中的首个字符,看看在S中是否处于首尾位置,如果是就去掉。把去掉后的新字符串设置为s,继续循环,从chars中的首个字符开始。如果不在,直接从chars第二个字符开始。一直循环到,s中首尾字符都不在chars中,则循环终止。
Python中strip函数几种用法_strip在python中的用法-CSDN博客
-
这些方法在处理用户输入、文件读取等场景中经常用到,可以有效地清理字符串的格式
(6)切分(split/rsplit)
split()
方法用于将字符串切分成多个子字符串,并返回一个包含切分后子字符串的列表。
.rsplit()
方法便是反向,从右向左去切分对象
[1] 默认切分符
- 如果不指定切分符,则默认使用空白作为切分符。空白可以是空格,可以是换行
| text = 'Hello, World!' |
| split_result = text.split() |
| print(split_result) |
| |
| text1 = """ |
| hello |
| world |
| """ |
| print(text1.split()) |
[2] 指定分隔符
- 可以通过传递一个分隔符参数给
split()
方法来指定切分符。
| text = 'apple,orange,banana' |
| split_result = text.split(',') |
| print(split_result) |
| |
- 在处理 CSV 格式的数据、日志文件等场景中,
split()
方法非常实用,可以将字符串按照指定的分隔符拆分成各个字段。
[3]指定切分次数
- 可以为.split()函数指定一个切分次数
- str.split('切分字符',指定次数)
| site = 'D:/A/B/C/D.TXT' |
| print(site.split('/')) |
| |
| |
| print(site.split('/', 1)) |
| |
| |
| |
| |
| |
| |
| print(site.rsplit('/',1)) |
| |
| |
(7)遍历字符串(for循环)
| text = 'Python' |
| for char in text: |
| print(char) |
| |
| |
| |
| |
| |
| |
| |
(8)字符串重复(*)
| original_str = 'ABC' |
| repeated_str = original_str * 3 |
| print(repeated_str) |
| |
(9)大小写转换(.upper() / .lower())
- 大小写转换,在验证码的场景下用的较多,平时常见的验证码都是随意大小写均可
[1]小写转大写(upper())
| text = 'hello' |
| uppercase_text = text.upper() |
| print(uppercase_text) |
| |
[2]大写转小写(lower())
| text = 'WORLD' |
| lowercase_text = text.lower() |
| print(lowercase_text) |
| |
[3]举例
| show_user = 'K2nF' |
| print(f"这是您需要输入的验证码:{show_user}") |
| input_user = input("请输入你看到的验证码,不区分大小写:>>>") |
| |
| if show_user.upper() == input_user.upper(): |
| |
| print("验证通过") |
| else: |
| print("验证失败") |
(10)首尾字符判断(.startswith() / .endswith())
[1]判断字符开头(startswith())
- startswith()判断字符串是否以括号内指定的字符开头,结果为布尔值True或False
| text = 'Python is fun' |
| result = text.startswith('Python') |
| print(result) |
| |
[2]判断字符结尾(endswith())
- endswith()判断字符串是否以括号内指定的字符结尾,结果为布尔值True或False
| text = 'Python is fun' |
| result = text.endswith('fun') |
| print(result) |
| |
- 之前讲到过 print() 函数的用法,这只是最简单最初级的形式,print() 还有很多高级的玩法,比如格式化输出。
[1] % 输出
- 使用
%
运算符进行格式化输出,可以在字符串中插入占位符,然后通过 %
运算符传入相应的值。
| |
| name = "Lea4ning" |
| age = 18 |
| height = 180.0 |
| |
| |
| print("My name is %s." % name) |
| |
| |
| |
| print("My age is %d." % age) |
| |
| |
| |
| print("My height is %f." % height) |
| |
| |
| |
| print("My height is %.2f." % height) |
| |
| |
| |
| number = 255 |
| print("Number in hex: %x." % number) |
| |
| |
| |
| print("My name is %s; My age is %d" % (name, age)) |
| |
- 在上例中,
%s
和 %d
是占位符,分别表示字符串和整数,而 (name, age)
是传入这两个占位符的实际值。
- 占位符类型
%s
:字符串
%d
:整数
%f
:浮点数
%x
:十六进制整数
- 使用
format
方法进行格式化输出,通过花括号 {}
表示占位符,然后调用 format
方法传入实际值
| name = "Lea4ning" |
| age = 18 |
| |
| print("My name is {}; My age is {}".format(name, age)) |
| |
| |
| print("My name is {0}; My age is {1};{0},{1}".format(name, age)) |
| |
| print("My name is {name}; My age is {age};{name},{age}".format(name, age)) |
- 在这个例子中,
{}
是占位符,它会按顺序依次填充传入 format
方法的值
[3] f + {} 输出
- 使用 f-string(f +
{}
)进行格式化输出,通过在字符串前加上 f
或 F
前缀,然后在字符串中使用 {}
表示占位符,并在 {}
中直接引用变量。
| name = "Lea4ning" |
| age = 18 |
| |
| print(f"My name is {name}; My age is {age}") |
| |
(12)拼接(.join)
- 从可迭代对象中取出多个字符串,然后按照指定的分隔符进行拼接,拼接的结果为字符串
| res_1 = '%'.join('hello') |
| print(res_1) |
| |
| |
| res_2 = '|'.join(['Lea4ning', '18', 'code']) |
| print(res_2) |
(13)替换(.replace())
| res_1 = 'my name is Lea4ning, my age is 18!' |
| res_1 = res_1.replace('18', '99') |
| print(res_1) |
| |
| |
| res_2 = 'my name is Lea4ning, my age is 18!' |
| res_2 = res_2.replace('my', 'MY', 1) |
| print(res_2) |
| m = 10 |
| n = 20 |
| res = str(m) + str(n) |
| print(res, type(res)) |
| m = res.replace(str(m), '') |
| n = res.replace(str(n), '') |
| print(m, n) |
(14)判断类型(.isdigit())
- 判断字符串是否是纯数字组成,返回结果为True或False
| str8 = '5201314' |
| res_1 = str8.isdigit() |
| print(res_1) |
| |
| str8 = '123g123' |
| res_2 = str8.isdigit() |
| print(res_2) |
【2】内置方法(熟悉)
(1)查找
[1]find
- 从指定范围内查找子字符串的起始索引,找得到则返回索引值,找不到则返回-1
| msg = 'tony say hello' |
| |
| |
| res = msg.find('o', 1, 3) |
| print(res) |
[2]rfind
| msg = 'tony say hello' |
| |
| |
| res = msg.rfind('o') |
| print(res) |
[3]index
| msg = 'tony say hello' |
| |
| |
| res = msg.index('o') |
| print(res) |
| print(msg.index('z',1,len(msg)+1)) |
| |
[4]rindex
| msg = 'tony say hello' |
| |
| |
| res = msg.rindex('o') |
| print(res) |
[5]count
| msg = 'tony say hello' |
| |
| |
| res = msg.count('o') |
| print(res) |
(2)填充
[1]center
| msg = 'tony' |
| |
| |
| res = msg.center(10, '-') |
| print(res) |
[2]ljust
| msg = 'tony' |
| |
| |
| res = msg.ljust(10, '-') |
| print(res) |
[3]rjust
| msg = 'tony' |
| |
| |
| res = msg.rjust(10, '-') |
| print(res) |
[4]zfill
| msg = 'Dream' |
| |
| |
| res = msg.zfill(10) |
| print(res) |
(3)制表符
| name = 'Lea4ning\thello' |
| print(name) |
| |
| location = "China\tFirst" |
| expanded_name = location.expandtabs(2) |
| print(expanded_name) |
(4)首字母大写(captalize)
| text = 'hello world' |
| capitalized_text = text.capitalize() |
| print(capitalized_text) |
(5)大小写翻转(swapcase)
| mixed_case = 'HeLLo WoRLd' |
| swapped_case = mixed_case.swapcase() |
| print(swapped_case) |
(6)单词首字母大写(title)
| sentence = 'the quick brown fox' |
| title_case = sentence.title() |
| print(title_case) |
【3】判断字符串类型
| name = 'Lea4ning521' |
| print(name.isalnum()) |
| print(name.isalpha()) |
| print(name.isidentifier()) |
| print(name.islower()) |
| print(name.isupper()) |
| print(name.isspace()) |
| print(name.istitle()) |
【三】列表类型(list)
【1】内置方法
(1)类型强转
- 但凡能被for循环遍历的数据类型都可以传给list()转换成列表类型
- list()会跟for循环一样遍历出数据类型中包含的每一个元素然后放到列表中
| |
| string = 'hello' |
| list_from_string = list(string) |
| print(list_from_string) |
| |
| |
| tuple_example = (1, 2, 3) |
| list_from_tuple = list(tuple_example) |
| print(list_from_tuple) |
| |
| |
| range_example = range(5) |
| list_from_range = list(range_example) |
| print(list_from_range) |
| |
(2)按索引存取值
[1]正向取值
| |
| numbers = [1, 2, 3, 4, 5] |
| first_number = numbers[0] |
| print(first_number) |
| |
[2]反向取值
| |
| numbers = [1, 2, 3, 4, 5] |
| last_number = numbers[-1] |
| print(last_number) |
| |
[3]索引取值无则报错
- 对于list来说,既可以按照索引取值,又可以按照索引修改指定位置的值,但如果索引不存在则报错
| |
| numbers = [1, 2, 3, 4, 5] |
| index_10 = numbers[10] |
| print(index_10) |
(3)切片
[1]顾头不顾尾
| |
| numbers = [1, 2, 3, 4, 5] |
| sliced_numbers = numbers[1:4] |
| print(sliced_numbers) |
| |
[2]步长
| |
| numbers = [1, 2, 3, 4, 5] |
| stepped_numbers = numbers[0:4:2] |
| print(stepped_numbers) |
| |
(4)计算长度
| |
| numbers = [1, 2, 3, 4, 5] |
| length = len(numbers) |
| print(length) |
| |
(5)成员运算
[1]in
| |
| numbers = [1, 2, 3, 4, 5] |
| contains_3 = 3 in numbers |
| print(contains_3) |
| |
[2]not in
| |
| numbers = [1, 2, 3, 4, 5] |
| not_contains_6 = 6 not in numbers |
| print(not_contains_6) |
| |
(6)增加
[1]默认追加(.append())
- append()默认追加到末尾(不管是什么类型的数据,都会当成一个整体元素填进去)
| |
| numbers = [1, 2, 3, 4, 5] |
| numbers.append(6) |
| print(numbers) |
| |
[2]一次性添加多个(.extend())
- extend()一次性在列表尾部添加多个元素、合并列表
| |
| list1 = [1, 2, 3] |
| list1.extend([5, 6]) |
| print(list1) |
| list1.extend(['a', 'b']) |
| print(list1) |
| list1.extend({'c': 9}) |
| print(list1) |
[3]指定位置添加(insert)
- insert()在指定位置添加元素(索引位置,不管是什么类型的数据,都会当成一个整体元素填进去)
| |
| list1 = [1, 2, 3] |
| list1.insert(0, '1') |
| print(list1) |
| |
(7)删除
[1]del
| |
| numbers = [1, 2, 3, 4, 5] |
| del numbers[2] |
| print(numbers) |
| |
[2]pop
- pop()默认删除列表最后一个元素,并将删除的值返回,括号内可以通过加索引值来指定删除元素
| |
| numbers = [1, 2, 3, 4, 5] |
| popped_value = numbers.pop(2) |
| print(popped_value) |
| print(numbers) |
[3]remove
- remove()括号内指名道姓表示要删除哪个元素,没有返回值
| |
| numbers = [1, 2, 3, 4, 3, 5] |
| numbers.remove(3) |
| print(numbers) |
- 在这个例子中,
remove(3)
删除了列表中的第一个值为 3 的元素。
- 如果值不存在,会引发
ValueError
异常。
- 这是与
pop()
不同的地方,pop()
是通过索引来删除元素的
(8)颠倒元素(reverse())
| |
| numbers = [1, 2, 3, 4, 5] |
| numbers.reverse() |
| print(numbers) |
- 在这个例子中,
reverse()
将列表中的元素颠倒,原来的第一个元素变成了最后一个,原来的最后一个元素变成了第一个
(9)元素排序(sort())
sort()
方法用于对列表进行排序,默认是升序排序。
| |
| numbers = [5, 2, 9, 1, 7] |
| numbers.sort() |
| print(numbers) |
- 如果需要降序排序,可以使用
reverse
参数:
| |
| numbers = [5, 2, 9, 1, 7] |
| numbers.sort(reverse=True) |
| print(numbers) |
- 需要注意的是,
sort()
方法会直接修改原列表,而不会返回一个新的排序后的列表。
(10)元素排序(sorted())
- 如果你需要保留原列表,可以使用
sorted()
函数
| |
| numbers = [5, 2, 9, 1, 7] |
| sorted_numbers = sorted(numbers) |
| print(sorted_numbers) |
| print(numbers) |
sort()
方法默认是按照元素的大小进行排序,如果需要自定义排序规则,可以使用 key
参数,传入一个函数
- 例如,按照元素的绝对值进行排序:
| |
| numbers = [-5, 2, -9, 1, 7] |
| numbers.sort(key=abs) |
| print(numbers) |
key
参数指定的函数将应用于列表中的每个元素,用于提取排序的关键字。
(10)遍历循环
- 遍历循环是对列表中的每个元素进行迭代或循环处理。常用的遍历方式有
for
循环和 while
循环。
[1]for
循环遍历列表
| |
| fruits = ['apple', 'banana', 'orange'] |
| for fruit in fruits: |
| print(fruit) |
| |
| |
| |
| |
[2]while
循环遍历列表
| |
| fruits = ['apple', 'banana', 'orange'] |
| index = 0 |
| while index < len(fruits): |
| print(fruits[index]) |
| index += 1 |
| |
| |
| |
| |
for
循环更加简洁,但 while
循环提供了更多的控制选项。
- 通常情况下,推荐使用
for
循环遍历列表。
[3]遍历时获取索引
- 如果需要同时获取元素的索引和值,可以使用
enumerate()
函数:
| |
| fruits = ['apple', 'banana', 'orange'] |
| for index, fruit in enumerate(fruits): |
| print(f"Index: {index}, Fruit: {fruit}") |
| |
| |
| |
| |
(11)步长操作
[1]正向步长
| |
| numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| result = numbers[::2] |
| print(result) |
| |
[2]反向步长
| |
| numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| result = numbers[::-2] |
| print(result) |
| |
[3]列表翻转
| |
| numbers = [1, 2, 3, 4, 5] |
| print(numbers[::-1]) |
| |
- 这些步长操作可以在遍历列表时提供更灵活的选项,根据需求选择不同的步长值以获取所需的元素。
(补充)字符串排序
- 我们常用的数字类型直接比较大小,但其实,字符串、列表等都可以比较大小
- 原理相同:都是依次比较对应位置的元素的大小,如果分出大小,则无需比较下一个元素
| |
| l1 = [1, 2, 3] |
| l2 = [2, ] |
| print(l2 > l1) |
| |
| |
| |
| s1 = 'abc' |
| s2 = 'az' |
| print(s2 > s1) |
| |
| |
| |
| l = ['A', 'z', 'adjk', 'hello', 'hea'] |
| l.sort() |
| print(l) |
- 当我们使用
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)类型强转
- 但凡能被for循环的遍历的数据类型都可以传给tuple()转换成元组类型
- 使用
tuple()
函数可以将其他可迭代对象转换为元组
| |
| numbers_list = [1, 2, 3, 4, 5] |
| numbers_tuple = tuple(numbers_list) |
| print(numbers_tuple) |
(2)索引取值
[1]正索引取值
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print(fruit_tuple[1]) |
[2]负索引取值
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print(fruit_tuple[-1]) |
[3]只能取不能改
- 与列表相同,如果索引不存在,会抛出
IndexError
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print(fruit_tuple[3]) |
| |
| print(fruit_tuple[0]) |
| fruit_tuple[1] = 'pineapple' |
| tuple1 = ('key', 'value', ['a', 'b']) |
| tuple1[2][0]= 'c' |
| print(tuple1) |
| |
| tuple1 = ('key', 'value', {'a': 'b'}) |
| tuple1[2]['a']= 'z' |
| print(tuple1) |
(3)切片(顾头不顾尾)
[1]顾头不顾尾
| |
| fruit_tuple = ('apple', 'banana', 'cherry', 'date', 'elderberry') |
| print(fruit_tuple[1:4]) |
[2]步长
| |
| numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) |
| print(numbers_tuple[::2]) |
(4)计算长度len()
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print(len(fruit_tuple)) |
(5)成员运算in / not in
[1]in
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print('banana' in fruit_tuple) |
| print('orange' not in fruit_tuple) |
[2]not in
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| print('orange' not in fruit_tuple) |
(6)遍历循环
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| for fruit in fruit_tuple: |
| print(fruit) |
| |
| |
| |
| |
(7)元组拼接(+)
| |
| tuple1 = (1, 2, 3) |
| tuple2 = ('a', 'b', 'c') |
| result_tuple = tuple1 + tuple2 |
| print(result_tuple) |
(8)元组重复(*)
| |
| fruit_tuple = ('apple', 'banana', 'cherry') |
| result_tuple = fruit_tuple * 2 |
| print(result_tuple) |
| |
【五】字典类型(dict)
【1】字典类型定义
- 字典(Dictionary)是一种无序的数据集合,使用键(key)和值(value)之间的映射关系来存储数据。
- 字典是Python中唯一的映射类型,其它语言中可能称为关联数组或哈希表。
- 字典的特点:
- 字典中的数据是无序的,不能通过索引来访问,而是通过键来访问。
- 字典中的键必须是不可变的,通常使用字符串、数字或元组作为键。
- 字典中的值可以是任意类型,包括数字、字符串、列表、字典等。
- 字典的创建使用花括号
{}
,并使用冒号 :
分隔键和值。
- 多个键值对之间使用逗号
,
分隔。
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
【2】定义
- 定义字典时,键和值之间使用冒号
:
分隔,多个键值对之间使用逗号 ,
分隔。
- 字典的键必须是不可变的,通常使用字符串、数字或元组作为键。
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| |
| 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']) |
[2]get取值
- 使用
get
方法可以根据键获取对应的值,如果键不存在,则返回指定的默认值(默认为None
)
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| print(person_info.get('name')) |
| |
| print(person_info.get('height')) |
| print(person_info.get('height', 175)) |
(2)计算长度
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| length = len(person_info) |
| print(length) |
(3)成员运算
- 使用
in
和not in
可以判断一个键是否存在于字典中
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| print('name' in person_info) |
| print('male' in person_info) |
| print('height' not in person_info) |
(4)增加
[0]赋值增加
| |
| dict1 = {} |
| dict1['a'] = 1 |
| print(dict1) |
| |
| |
| dict1 = {'b':2,'c':3} |
| dict1['a'] = 1 |
| print(dict1) |
[1]新增键值对(update())
- 使用
update
方法可以批量新增键值对,如果键已经存在,则更新对应的值
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| person_info['height'] = 175 |
| print(person_info) |
[2]批量新增键值对(update())
- 使用
update
方法可以批量新增键值对,如果键已经存在,则更新对应的值
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| person_info.update({'height': 175, 'weight': 70}) |
| print(person_info) |
[3]增加值并返回值(setdefault())
setdefault(key, default)
方法用于获取指定键的值,如果键不存在,则返回默认值,并在字典中添加键值对。
| |
| person_info = {'name': 'Tony', 'age': 25} |
| |
| |
| gender = person_info.setdefault('gender', 'male') |
| print(gender) |
| print(person_info) |
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| add_dict = person_info.setdefault('key','value') |
| print(add_dict) |
| print(person_info) |
- 如果字典中存在键
'gender'
,则 setdefault()
方法返回对应的值;
- 如果不存在,则添加新键值对
'gender': 'male'
并返回默认值 'male'
(5)删除
[1]按键删除(del())
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| del person_info['age'] |
| print(person_info) |
[2]弹出键值对(pop())
- 使用
pop
方法可以根据键弹出字典中的键值对,同时返回被弹出的值
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| popped_value = person_info.pop('age') |
| print(popped_value) |
| print(person_info) |
[3]清空字典(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) |
| print(person_info) |
popitem()
在 Python 3.7+ 中删除的是字典中的“末尾”键值对,但在旧版本的 Python 中,删除的并不是末尾的键值对。
- 所以在使用
popitem()
时要注意版本兼容性。
(6)键对(keys())
- 使用
keys
方法可以获取字典中所有的键,返回一个可迭代的视图对象
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| keys = person_info.keys() |
| print(keys) |
(7)值对(values())
- 使用
values
方法可以获取字典中所有的值,返回一个可迭代的视图对象
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| values = person_info.values() |
| print(values) |
(8)键值对(items())
- 使用
items
方法可以获取字典中所有的键值对,返回一个可迭代的视图对象
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| items = person_info.items() |
| print(items) |
(9)遍历循环
[1]只遍历key
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| for key in person_info: |
| print(key) |
| |
| |
| |
| |
[2]只遍历value
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| for value in person_info.values(): |
| print(value) |
| |
| |
| |
| |
[3]遍历key和value
| |
| person_info = {'name': 'Dream', 'age': 25, 'gender': 'male'} |
| for key, value in person_info.items(): |
| print(f'{key}: {value}') |
| |
| |
| |
| |
(10)字典排序(sorted())
- 字典的排序是通过字典的键来进行的,使用
sorted()
函数可以对字典进行排序。
| |
| my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 1} |
| |
| |
| sorted_dict = sorted(my_dict.items()) |
| print(sorted_dict) |
| |
- 在示例中,
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) |
| |
- 在这个示例中,
key
参数指定了按值排序,并使用了 lambda
函数提取元组中的第二个元素(值)作为排序的关键字。
【六】集合类型(set)
【1】集合类型定义
- 集合(Set)是 Python 中的一种无序且不重复的数据类型。
- 集合类型的定义使用大括号
{}
,元素之间使用逗号 ,
分隔。
【2】定义
- 集合的定义方式与示例中的方式相同,使用大括号
{}
并将元素用逗号 ,
分隔。
| |
| my_set = {1, 2, 3, 4, 5} |
| print(my_set) |
【3】内置方法
(0)类型强转
- 但凡能被for循环的遍历的数据类型(强调:遍历出的每一个值都必须为不可变类型)都可以传给set()转换成集合类型
| |
| my_list = [1, 2, 2, 3, 4, 4, 5] |
| |
| |
| my_set = set(my_list) |
| print(my_set) |
| |
- 在这个示例中,
my_list
是一个包含重复元素的列表,通过使用 set()
将其转换为集合,得到了一个去重后的集合 my_set
。
(1)添加元素
[1] 添加单个元素(add())
add(element)
方法用于向集合中添加单个元素。
| |
| my_set = {1, 2, 3} |
| my_set.add(4) |
| print(my_set) |
[2]添加多个元素(update())
update(iterable)
方法用于向集合中添加多个元素,参数是一个可迭代对象。
| |
| my_set = {1, 2, 3} |
| my_set.update([3, 4, 5]) |
| print(my_set) |
(2)删除元素
[1] 删除指定元素(remove())
remove(element)
方法用于移除集合中的指定元素,如果元素不存在则会引发 KeyError。
| |
| my_set = {1, 2, 3, 4, 5} |
| my_set.remove(3) |
| print(my_set) |
[2] 删除指定元素(discard())
discard(element)
方法用于移除集合中的指定元素,如果元素不存在则不会引发错误。
| |
| my_set = {1, 2, 3, 4, 5} |
| my_set.discard(3) |
| print(my_set) |
[3] 随机删除元素(pop())
pop()
方法用于随机移除集合中的一个元素,如果集合为空则引发 KeyError。
| |
| my_set = {1, 2, 3, 4, 5} |
| removed_element = my_set.pop() |
| print(removed_element) |
| print(my_set) |
| |
| |
| |
| my_set = {'a', 'b', 'v'} |
| removed_element = my_set.pop() |
| print(removed_element) |
| print(my_set) |
| |
| |
(3)集合操作
[1] 并集(union() / | )
union(*others)
方法返回当前集合与其他集合的并集。
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| union_set = set1.union(set2) |
| print(union_set) |
| |
| |
| set1 = {1, 2, 3} |
| set2 = {4, 5, 6} |
| print(set1 | set2) |
[2] 交集(intersection() / & )
intersection(*others)
方法返回当前集合与其他集合的交集。
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| intersection_set = set1.intersection(set2) |
| print(intersection_set) |
| |
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| print(set1 & set2) |
[3] 差集(difference() / - )
difference(*others)
方法返回当前集合与其他集合的差集。
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| difference_set = set1.difference(set2) |
| print(difference_set) |
| |
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| print(set1 - set2) |
| print(set2 - set1) |
[4] 对称差集(symmetric_difference() / ^)
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| symmetric_difference_set = set1.symmetric_difference(set2) |
| print(symmetric_difference_set) |
| |
| |
| set1 = {1, 2, 3} |
| set2 = {3, 4, 5} |
| print(set1 ^ set2) |
[5]父集
| set1 = {1, 2, 3, 4, 5} |
| set2 = {2, 4} |
| |
| |
| is_superset = set1.issuperset(set2) |
| print(is_superset) |
| |
[6]子集
| set1 = {1, 2, 3, 4, 5} |
| set2 = {2, 4} |
| |
| |
| is_subset = set2.issubset(set1) |
| print(is_subset) |
| |
[7]判断(==
)
| set1 = {1, 2, 3, 4, 5} |
| set2 = {2, 4} |
| |
| |
| is_equal = set1 == set2 |
| print(is_equal) |
| |
(4)去重
- 只能针对不可变类型
- 集合本身是无序的,去重之后无法保留原来的顺序
| l_old = ['a', 'b', 1, 'a', 'a'] |
| s = set(l_old) |
| print(s) |
| |
| |
| l_new = list(s) |
| print(l_new) |
| |
| |
| |
| |
| 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) |
| |
(6)遍历循环
| my_set = {1, 2, 3, 'a', 'b'} |
| |
| |
| for item in my_set: |
| print(item) |
| |
(7)成员运算
[1]in
| is_in_set = 'a' in my_set |
| print(is_in_set) |
| |
[2]not in
| is_not_in_set = 6 not in my_set |
| print(is_not_in_set) |
| |
【七】案例
| |
| s = 'dream say hello hello hello sb sb sb sb jerry jerry nice nice nice' |
| dict_data = {} |
| list_str = s.split() |
| set_str = set(list_str) |
| for i in set_str: |
| dict_data.update({i: s.count(i)}) |
| print(dict_data) |
| |
| s = 'dream say hello hello hello sb sb sb sb jerry jerry nice nice nice' |
| dict_s = {} |
| for i in s: |
| if i not in dict_s: |
| dict_s[i] = 1 |
| else: |
| dict_s[i] += 1 |
| print(dict_s) |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了