Python函数(详解)

文章目录

一、Python基础

1.1、函数加括号 + 函数不加括号

函数名后面加括号 (参数)表示调用该函数;
函数名后面不加括号表示引用函数对象本身;

import numpy as np

array = np.array([[1, 2, 3], [4, 5, 6]])
max_value1 = np.max(array)  # 获取数组中的最大值
max_value2 = array.max  # 获取数组中的最大值
max_value3 = array.max()  # 获取数组中的最大值
print(max_value1, max_value2, max_value3)

"""
6 
<built-in method max of numpy.ndarray object at 0x00000199BB886630> 
6
"""

1.2、数据类型:整型 + 浮点型 + 复数 + 布尔 + 空值 + 字符串

  • 整型(int):表示整数,包括正整数和负整数。
  • 浮点型(float):表示带有小数点的数值。如:科学记数法 3.14E2 = 3.14 * 10^2 = 314
  • 复数(complex):由实部和虚部构成的数值。如:a + bj = complex(a, b)
  • 布尔类型(bool):表示逻辑值,包括True和False。True为1,False为0
  • 空值(None): 表示不存在的对象或尚未赋值的变量。
  • 字符串类型(str):如:空字符串为False,非空字符串为True
    • 使用单引号(' hello ')双引号(" python ")来创建字符串。
    • 字符串是由字符组成的序列,Python 中没有单独的字符类型,字符也是字符串的一种。

1.3、数据结构:列表 + 元组 + 字典 + 集合

  • 列表(list):有序的可变序列。—— 可以存储任意类型的数据,使用方括号([])来创建,可以通过索引访问和修改其中的元素。
  • 元组(tuple):有序的不可变序列。—— 可以存储任意类型的数据,使用圆括号(())来创建,一旦创建后,不能修改其内容。
  • 字典(dict):无序的键值对的集合。—— 用于存储具有映射关系的数据,使用花括号({})来创建,每个键值对由键和值组成,通过键来访问对应的值。
  • 集合(set):无序的不重复元素的集合。—— 用于存储不重复的数据,使用花括号({})来创建,可以进行集合运算(交集、并集、差集等)。

1.4、数据类型(可变 + 不可变)

在Python中,数据类型可分为可变(mutable)和不可变(immutable)两种。

1.4.1、可变 - 数据类型 —— 可以在原地修改其内容,而不会创建新的对象(列表 + 集合 + 字典)

可变数据类型(Mutable)可以在原地修改其内容,而不会创建新的对象。如:列表、集合、字典。

# 列表
list1 = [1, 2, 3]
print("Before modification:", id(list1))  # Before modification : 2410633776192
list1.append(4)  # 在原地修改列表 a
print("After modification:", id(list1))   # After modification  : 2410633776192

# 集合
set1 = {1, 2, 3}
print("Before modification:", id(set1))  # Before modification  : 2410634053440
set1.add(4)  # 在原地修改集合
print("After modification:", id(set1))   # After modification   : 2410634053440

# 字典
dict1 = {'a': 1, 'b': 2}
print("Before modification:", id(dict1))  # Before modification : 2410633737344
dict1['c'] = 3  # 在原地修改字典
print("After modification:", id(dict1))   # After modification  : 2410633737344

1.4.2、不可变 - 数据类型 —— 创建后不能修改其内容,每次修改都会生成一个新的对象(整数 + 浮点数 + 字符串 + 元组)

不可变数据类型(Immutable)一旦创建就不能修改其内容,每次对不可变对象进行修改操作,都会生成一个新的对象。如:整数、浮点数、字符串、元组。

# 整数
int1 = 10
print("Before modification:", id(int1))         # Before modification   : 1660585536080
int1 += 1  # 将整数 a 加1,实际上是创建了一个新的整数对象
print("After modification:", id(int1))          # After modification    : 1660585536112

# 浮点数
float1 = 3.14
print("Before modification:", id(float1))       # Before modification   : 1660590708464
float1 *= 2  # 将浮点数 b 乘2,实际上是创建了一个新的浮点数对象
print("After modification:", id(float1))        # After modification    : 1660594531152

# 字符串
string1 = "hello"
print("Before modification:", id(string1))      # Before modification   : 1660594841840
string1 += " world"  # 将字符串 s 连接上 " world",实际上是创建了一个新的字符串对象
print("After modification:", id(string1))       # After modification    : 1660594842032

# 元组
tuple1 = (1, 2, 3)
print("Before modification:", id(tuple1))       # Before modification   : 1660592804416
tuple1 += (4, 5)  # 将元组 t 与 (4, 5) 进行连接,实际上是创建了一个新的元组对象
print("After modification:", id(tuple1))        # After modification    : 1660590584592

1.5、序列 —— 是一种有序的数据结构(字符串 + 列表 + 元组)

在Python中,序列是一种有序的数据结构,提供了丰富的方法和操作符来进行元素访问、添加、删除、切片等操作。

序列的特点:
(1)有序性:序列中的元素按照特定的顺序排列,每个元素都有一个唯一的位置或索引。

  • 字符串(有序不可变序列)
  • 元组(有序不可变序列)
  • 列表(有序可变序列)
    • range类型:list(range(10))
    • map类型:list(map(int, [23.2, 33.1]))

(2)可变性:某些序列是可变的,可以修改其中的元素(如列表),而另一些序列是不可变的,无法修改其中的元素(如元组、字符串)。
(3)可迭代性:序列可以被迭代遍历。如:使用for循环遍历序列中的每个元素。

1.6、容器(Container) —— 用于存储多个元素的对象(列表、元组、集合、字典)

容器(Container)用于存储多个元素的对象。如:列表、元组、集合、字典。

两种容器类型:

  • 有序容器:元素按照一定顺序排列的容器。
    • 有序可变容器:列表
    • 有序不可变容器:元组
  • 无序容器:元素没有固定顺序的容器。
    • 无序可变容器:
      • 集合(无序可变容器) —— 集合中的元素是不可变的,但可以通过添加或删除元素而改变
      • 字典(无序可变容器) —— 字典中的键是不可变的,但可以通过添加或删除键而改变
    • 无序不可变容器:无

1.7、可迭代对象 + 迭代器 + 生成器

  • 可迭代对象(iterable)不是迭代器,使用 iter() 函数可以将可迭代对象转为迭代器。
  • 迭代器(iterator)是可迭代对象的一种特殊形式
  • 生成器(yield)本质上是一个迭代器

Python中的for循环就是基于可迭代对象和迭代器实现的,它能够遍历容器对象中的每一个元素。

"""使用内置函数 isinstance 判断对象为可迭代对象 or 迭代器"""

from collections import Iterable, Iterator

print(isinstance([], Iterable))		# True
print(isinstance([], Iterator))		# False。因为list还没有被转为迭代器,仅是可迭代对象
# (1)可迭代对象
iterable_obj = [1, 2, 3, 4, 5]
# 使用 for 循环迭代
print("iterable object:")
for item in iterable_obj:
    print(item)

##################################################
# (2)迭代器 ———— 使用 iter() 函数将可迭代对象转为迭代器。
iterator_obj = iter(iterable_obj)
# 使用 next() 函数逐个访问元素
print("iterator object:")
print(next(iterator_obj))  # 输出第一个元素:1
print(next(iterator_obj))  # 输出第二个元素:2
print(next(iterator_obj))  # 输出第三个元素:3

python:可迭代对象、迭代器、生成器(全解)

1.7.1、可迭代对象(iterable):列表 + 元组 + 集合 + 字典 + 字符串

可迭代对象(iterable)通过迭代(循环)访问其元素的对象。包括:列表、元组、集合、字典、字符串。

可迭代对象的两种访问方式:

  • (1)__ iter __ ( )方法,迭代元素。如:for index in object
  • (2)__ getitem __ ( )方法,访问元素。如:object[index]
class MyIterable1:
    # (1)使用 __iter__() 方法迭代访问:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return iter(self.data)


class MyIterable2:
    # (2)使用 __getitem__() 方法访问元素:
    def __init__(self, data):
        self.data = data

    def __getitem__(self, index):
        return self.data[index]

    def __len__(self):
        return len(self.data)


if __name__ == "__main__":
    my_iterable1 = MyIterable1([1, 2])  # 创建一个可迭代对象
    for item in my_iterable1:
        print("my_iterable1", item)

    my_iterable2 = MyIterable2([1, 2])  # 创建一个可迭代对象
    for i in range(len(my_iterable2)):
        print("my_iterable2", my_iterable2[i])
        
"""
my_iterable1 1
my_iterable1 2

my_iterable2 1
my_iterable2 2
"""

1.7.2、迭代器(iterator)

迭代器(iterator):是一种对象,它实现了迭代协议。用于在迭代过程中逐个返回其元素,而不需要在内存中同时存储所有元素。

迭代器对象具有两个方法:

  • (1)__ iter __() 方法:返回迭代器本身,以便在 for 循环等上下文中使用。
  • (2)__ next __() 方法:返回迭代器的下一个元素;
    • 若没有下一个元素,则引发 StopIteration 异常。
class MyIterator:
    def __init__(self, data):
        self.data = data
        self.index = 0

    def __iter__(self):
        # 返回迭代器对象自身
        return self

    def __next__(self):
        if self.index >= len(self.data):
            # 如果已经遍历完所有元素,则抛出 StopIteration 异常
            raise StopIteration
        else:
            # 返回下一个元素,并将索引指向下一个位置
            result = self.data[self.index]
            self.index += 1
            return result


if __name__ == "__main__":
    # 创建一个可迭代对象
    my_iterable = MyIterator([1, 2])

    # (1)使用 for 循环迭代元素
    for item in my_iterable:
        print("my_iterable", item)

    # (2)使用 next() 函数遍历迭代器
    while True:
        print(next(my_iterable))
"""
my_iterable 1
my_iterable 2

Traceback (most recent call last):
  File "F:\py\main222.py", line 31, in <module>
    print(next(my_iterable))
  File "F:\py\main222.py", line 13, in __next__
    raise StopIteration
StopIteration
"""

1.7.3、生成器(yield)

生成器(yield):是一种特殊类型的迭代器。在需要时逐个生成值,而不是一次性生成所有值并将它们存储在内存中。

  • 生成器函数:使用 yield 语句返回一个值,但是并不结束函数的执行,而是将函数的状态保存下来,以便下次调用 next() 函数时从上次 yield 语句的位置继续执行。
    • 每次调用生成器函数时,它会返回一个生成器对象。
    • 生成器用关键字 yield 返回值,而普通函数用 return 返回值。
  • 生成器对象:可以通过 next() 函数来获取下一个值。
def my_generator():
    yield 1
    yield 2
    yield 3


if __name__ == "__main__":
    # 创建一个生成器对象
    gen = my_generator()

    # 使用 next() 函数获取生成器的值
    print(next(gen))  # 输出:1
    print(next(gen))  # 输出:2

二、Python运算符

2.1、算术运算符 —— 用于执行基本的数学运算。

序列运算符名称说明举例结果数据类型
【1】+(1)对于数字:求和。c = 1 + 2c = 3int型
【1】+(2)对于序列类型(如:字符串):拼接操作str = 'a' + 'b'str = 'ab'字符串型
2-求差值c = 1 - 2c = -1int型
【3】*(1)对于数字:求积。c = 2 * 3c = 6int型
【3】*(2)对于序列类型(如:字符串):重复操作str = 'a' * 3str = 'aaa'字符串型
4/求商(两个整数或浮点数相除,结果为float型)c = 3 / 2c = 1.5浮点型
5%取模求余数c = 3 % 2c = 1int型
6**幂运算求次幂c = 3 ** 2c = 9int型
【7】//地板除法(向下取整)两个整数相除,结果为int型c = 3 // 2c = 1int型
【7】//地板除法(向下取整)除数或被除数为float类型,结果为float型c = 3 // 2.0c = 1.0浮点型
a = 10
b = 3

print("加法:", a + b)     # 输出: 13
print("减法:", a - b)     # 输出: 7
print("乘法:", a * b)     # 输出: 30
print("除法:", a / b)     # 输出: 3.3333333333333335
print("取模:", a % b)     # 输出: 1
print("幂运算:", a ** b)   # 输出: 1000
############################################################
print("加法(序列):", "a" + "b")                # 输出: ab
print("乘法(序列):", "a" * 3)                  # 输出: aaa
############################################################
print("地板除法(向下取整):", a // b)            # 输出: 3
print("地板除法(向下取整):", a // float(b))     # 输出: 3.0

2.2、关系运算符 —— 用于比较两个值之间的关系。

常见的关系运算符包括:

  • 等于(==):判断两个值是否相等,若相等则返回 True,否则返回 False。
  • 不等于(!=):判断两个值是否不相等,若不相等则返回 True,否则返回 False。
  • 大于(>):判断左边的值是否大于右边的值,若成立则返回 True,否则返回 False。
  • 小于(<):判断左边的值是否小于右边的值,若成立则返回 True,否则返回 False。
  • 大于等于(>=):判断左边的值是否大于或等于右边的值,若成立则返回 True,否则返回 False。
  • 小于等于(<=):判断左边的值是否小于或等于右边的值,若成立则返回 True,否则返回 False。
x = 5
y = 10

print(x == y)  # 等于		False
print(x != y)  # 不等于		True
print(x > y)   # 大于		False
print(x < y)   # 小于		True
print(x >= y)  # 大于等于	False
print(x <= y)  # 小于等于	True

2.3、逻辑运算符 —— 用于对布尔值进行操作。

常用的逻辑运算符包括:

  • 与运算(and):若两个操作数都为 True,则结果为 True;否则为 False。
  • 或运算(or):若两个操作数中有任意一个为 True,则结果为 True;否则为 False。
  • 非运算(not):用于对布尔值取反。not True的结果为False,not False的结果为True。
a = True
b = False

print(a and b)  # 与运算		False
print(a or b)  	# 或运算		True
print(not a)  	# 非运算		False

2.4、位运算符 —— 用于对二进制数进行操作。

常见的位运算符包括:

  • 按位与(&):对两个数的每一位进行与操作,只有当对应位置的两个数都为 1 时,结果位才为 1。
  • 按位或(|):对两个数的每一位进行或操作,只要对应位置的两个数中有一个为 1,结果位就为 1。
  • 按位异或(^):对两个数的每一位进行异或操作,当对应位置的两个数不同时,结果位为 1;否则为 0。
  • 按位取反(~):对数的每一位进行取反操作,即 0 变为 1,1 变为 0。
  • 左移(<<):将一个数的所有位向左移动指定的位数,右侧空出的位用 0 填充。
  • 右移(>>):将一个数的所有位向右移动指定的位数,左侧空出的位取决于原来的数是正数还是负数。正数用 0 填充,负数用 1 填充。
x = 0b1010   # 十进制为 10
y = 0b1100   # 十进制为 12

print(bin(x & y))   # 按位与		0b1000
print(bin(x | y))   # 按位或		0b1110
print(bin(x ^ y))   # 按位异或	0b110
print(bin(~x))      # 按位取反	-0b1011
print(bin(x << 2))  # 左移		0b101000
print(bin(y >> 1))  # 右移		0b110

2.5、成员运算符 —— 用于检查指定的值是否存在于数据结构中。

常见的成员运算符包括:

  • 存在(in):若指定的值存在于数据结构中,则返回 True,否则返回 False。
  • 不存在(not in):若指定的值不存在于数据结构中,则返回 True,否则返回 False。
my_list = [1, 2, 3, 4, 5]

print(3 in my_list)      # True
print(3 not in my_list)  # False

2.6、身份运算符 —— 用于检查两个对象的内存地址是否相同,即它们是否引用同一个对象。

常见的身份运算符包括:

  • 地址相同(is):若两个变量引用同一个对象,则返回 True,否则返回 False。
  • 地址不相同(is not):若两个变量引用的不是同一个对象,则返回 True,否则返回 False。
x = [1, 2, 3]
y = [1, 2, 3]
z = x

print(x is y)       # False,虽然值相同,但是它们引用的是不同的对象
print(x is z)       # True,变量 x 和 z 引用的是同一个对象
print(x is not y)   # True
print(x is not z)   # False

2.7、三元条件运算符 —— 用于根据条件的真假返回两个值中的一个。

基本形式为:value_if_true if condition else value_if_false
其中,condition 是一个表达式,若结果为真,则返回 value_if_true;否则返回 value_if_false。

x = 5
result = "even" if x % 2 == 0 else "odd"
print(result)  	# 输出: odd,因为5是奇数

三、Python数据结构:列表、元祖、集合、字典、链表

1、列表(list)的常用操作(15+9函数)—— 列表是一个有序可变序列。

一般来说,有序序列类型都支持索引,切片,相加,相乘,成员操作。

  • 不可变数据类型布尔类型(bool)、整型(int)、字符串(str)、元组(tuple)
  • 可变数据类型列表(list)、集合(set)、字典(dict)
序号函数说明
0list1 = []创建空列表
0list1 = list()创建空列表
1list2 = [元素]创建列表。输入参数可以是任意类型
1list2 = list(元素)创建列表。输入参数可以是任意类型
——————
2list[index]索引(负数表示倒叙)
3list[start, end]切片(获取指定范围元素)
4list[::-1]逆序输出(步长为1)
——————
5list.append(元素)在列表末尾添加任意类型的一个元素
6list.extend(元素)添加可迭代序列
7list.insert(index, 元素)在指定位置插入一个元素
——————
8list.remove(元素)删除指定元素。(1)若有多个相同元素,则只删除第一个元素。(2) 若不存在,则系统报错。
9list.pop(index)删除指定位置元素。默认删除最后一项。
10del list(index)删除指定位置元素
11list.clear()清空内容,返回空列表
——————
12list.index(元素)索引元素位置。(1)若有多个相同元素,则只返回第一个元素的位置。(2)若不存在,则系统报错。
13list.count(元素)计算指定元素出现的次数
14list.reverse()逆序输出
15list.sort(*, key=None, reverse=False)(1)默认从小到大排列。(2)reverse=True 表示从大到小排序。
——————
(1)len(list)元素个数
(2)type(list)查看数据类型
(3)max(list)返回最大值(不能有嵌套序列)
(4)min(list)返回最小值(不能有嵌套序列)
(5)list(tuple)将元组转换为列表
(6)list1 + list2+ 操作符(拼接)
(7)list * 3* 操作符(重复)
(8)元素 in list(in / not in)成员操作符(判断给定值是否在序列中)
(9)for i in list:遍历

2、元组(tuple)的常用操作(7+9函数)—— 元组是一个有序不可变序列。

(1)Python 的元组与列表类似,不同之处在于元组的元素不能修改(不可变)。所谓元组不可变是指元组所指向的内存中的内容不可变。
(2)元组使用小括号 ( ),列表使用方括号 [ ]。
(3)一般来说,有序序列类型都支持索引,切片,相加,相乘,成员操作。
(4)元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。 如:整型:tup1 = (50) 元组:tup1 = (50,)

  • 不可变数据类型布尔类型(bool)、整型(int)、字符串(str)、元组(tuple)
  • 可变数据类型列表(list)、集合(set)、字典(dict)
序号函数说明
0tuple1 = ()创建空元组
0tuple1 = tuple()创建空元组
1tuple2 = (元素)创建列表。输入参数可以是任意类型
——————
2tuple[index]索引(负数表示倒叙)
3tuple[start, end]切片(获取指定范围元素)
4tuple[::-1]逆序输出(步长为1)
——————
5del tuple删除整个元组,不可以指定元素。删除后若打印变量,则系统报错(未定义)。
——————
6tuple.index(元素)索引元素位置。(1)若有多个相同元素,则只返回第一个元素的位置。(2)若不存在,则系统报错。
7tuple.count(元素)计算指定元素出现的次数
——————
(1)len(tuple)元素个数
(2)type(tuple)查看数据类型
(3)max(tuple)返回最大值(不能有嵌套序列)
(4)min(tuple)返回最小值(不能有嵌套序列)
(5)list(iterable)将可迭代系列转换为元组。
(6)tuple1 + tuple2+ 操作符(拼接)
(7)tuple * 3* 操作符(重复)
(8)元素 in tuple(in / not in)成员操作符(判断给定值是否在序列中)
(9)for i in tuple:遍历

3、集合(set)的常用操作(7+4函数)—— 集合是一个不重复元素的无序可变序列。

无序:赋值后,各元素位置将随机输出。
不重复:赋值变量时,若存在重复元素,系统会自动去除,只保留一个。

  • set(str) 对字符串去重
  • set(tuple)对元组去重
  • set(list)对列表去重。
    备注:字符串、元祖、列表是有序序列
    备注:无法对无序序列进行去重。
序号函数说明
0set1 = set()创建空集合
1set2 = {元素1, 元素2}创建集合
1set2 = set({元素1, 元素2})创建集合。输入参数可以是任意类型
——————
2set.add(元素)(只能添加一个元素)将元素添加到集合中。若元素存在,则不进行任何操作。
3set.update(元素)(添加多个元素)将元素添加到集合中。(1)参数可以是列表,元组,字典等。(2)若是字符串,将按字符拆分后再添加。
4set.copy()浅拷贝
——————
4set.remove(元素)删除指定元素。若元素不存在,则系统报错。
5set.discard(元素)删除指定元素。若元素不存在,则不进行任何操作。
6set.pop()随机删除一个元素。(1)对集合进行无序排列,然后删除第一个元素。(2)若指定元素,则系统报错。
7set.clear()清空内容,返回空集合
——————
(1)len(set)元素个数
(2)type(set)查看数据类型
(3)元素 in set(in / not in)成员操作符(判断给定值是否在序列中)
(4)for i in set:遍历

4、字典(dict)的常用操作(14+4函数)—— 字典是一个无序可变序列。

(2)键必须是唯一的(不可变数据类型),但值可以取任意数据类型。
(3)不支持索引、切片、重复和连接操作。

  • 不可变数据类型布尔类型(bool)、整型(int)、字符串(str)、元组(tuple)
  • 可变数据类型列表(list)、集合(set)、字典(dict)
序号函数说明
0dict1 = {}创建空字典
0dict1 = dict()创建空字典
1dict2 = {key1: value1, key2: value2}创建字典
1dict2 = dict({key: value, key2: value2})创建字典
——————
2dict.keys()查看字典中所有的key值
3dict.values()查看字典中所有的value值
4dict.items()查看字典中所有的key-value值
5dict(key)获取指定key对应的value值。若key值不存在,程序会报错。
6dict.get(key, default=None)获取指定key对应的value值。若key不存在,返回设置的default。
7dict.copy()浅拷贝
——————
8dict(key) = value若key存在,更新value值。若不存在,新增key-value值。
9dict1.update(dict2)添加元素(可同时添加多对)。若key存在,则更新value值。
10dict.setdefault(key, default=None)若key存在,既不新增也不更新value值。若key不存在,将会添加键,并将value值设为default。
——————
11dict.pop(key)弹出指定的key-value值
12dict.popitem()删除最后一个key-value
13dict.clear()清空字典内容,返回空字典
14del dict[key]删除指定的key-value值。
——————
(1)len(dict)列表元素个数
(2)type(dict)查看数据类型
(3)'key1' in dict or 'key1' in dict.keys判断给定值是否在字典的key中(默认:dict.keys())
(4)'value1' in dict.values()判断给定值是否在字典的value中
(5)'dict.has_key('name')判断字典中是否有指定的key元素
(5)for i in dict:遍历字典的key值(默认:dict.keys())

5、链表的常用操作(8个函数)—— 链表是一个非连续存储的线性表(节点 = 数据域 + 指针域)。

  • 在C/C++中,通常采用指针+结构体来实现链表;而在Python中,则采用引用+类来实现链表。
  • 常用的数据结构:数组、链表(一对一)、栈和队列、哈希表、树(一对多)、图(多对多)。列表与链表的对比

链表(Linked List)是一种线性表数据结构,使用一组任意的存储单元(不是进行连续存储的。),来存储一组具有相同类型的数据。

链表由多个元素组成,每个元素都是一个对象,每个对象称为一个节点。每个节点包含两个部分:左边存储着自定义数据(数据域),右边存储着下一个节点的链接地址(指针域)。

  • 通过各个节点之间的相互连接,最终串联成一个链表。
  • (1)单链表:它的每个链节点指向下一个链节点。
  • (2)双向链表(Doubly Linked List):它的每个链节点中有两个指针,分别指向直接后继和直接前驱。
  • (3)循环链表(Circular Linked List):它的最后一个链节点指向第一个链节点,形成一个环。
    在这里插入图片描述

链表的常见操作

链表的常见操作说明
is_empty()链表是否为空
length()链表长度
travel()遍历整个链表
add(item)链表头部添加元素
append(item)链表尾部添加元素
insert(pos, item)指定位置添加元素
remove(item)删除节点
search(item)查找节点是否存在
算法实现步骤+图解

具体代码:

class Node(object):
    """单链表的节点类,即 ListNode 类。定义了两个实例变量"""

    def __init__(self, elem):
        self.elem = elem
        self.next = None


class SingleLinkList(object):
    """单链表的链表类,即 LinkedList 类。定义了常用操作"""

    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        """判断链表是否为空"""
        return self.__head is None

    def length(self):
        """链表长度"""
        cursor = self.__head
        count = 0
        while cursor is not None:
            count += 1
            cursor = cursor.next
        return count

    def travel(self):
        """遍历链表"""
        cursor = self.__head
        while cursor is not None:
            print(cursor.elem, end=' ')
            cursor = cursor.next

    def add(self, elem):
        """链表头部添加元素"""
        node = Node(elem)
        node.next = self.__head
        self.__head = node

    def append(self, elem):
        """链表尾部添加元素"""
        node = Node(elem)
        if self.is_empty():
            self.__head = node
        else:
            cursor = self.__head
            while cursor.next is not None:
                cursor = cursor.next
            cursor.next = node

    def insert(self, pos, elem):
        """在指定位置插入元素"""
        node = Node(elem)
        if pos <= 0:
            self.add(elem)
        elif pos > (self.length() - 1):
            self.append(elem)
        else:
            cursor = self.__head
            count = 0
            while count < pos - 1:
                count += 1
                cursor = cursor.next
            node.next = cursor.next
            cursor.next = node

    def remove(self, elem):
        """删除元素"""
        cursor = self.__head
        pre = None
        while cursor is not None:
            if cursor.elem == elem:
                if cursor == self.__head:
                    self.__head = cursor.next
                    break
                else:
                    pre.next = cursor.next
                    break
            else:
                pre = cursor
                cursor = cursor.next

    def search(self, elem):
        """查找元素"""
        cursor = self.__head
        while cursor is not None:
            if cursor.elem == elem:
                return True
            else:
                cursor = cursor.next
        else:
            return False


if __name__ == "__main__":
    link1 = SingleLinkList()
    print(link1.is_empty())
    print(link1.length())
    
    link1.append(1)
    link1.append(2)
    link1.add(6)
    link1.insert(1, 7)
    link1.insert(-1, 8)
    link1.travel()
    print()
    print(link1.travel())
    
    link1.remove(9)
    link1.travel()
    print()
    print(link1.travel())


"""
True
0
8 6 7 1 2
8 6 7 1 2 None
8 6 7 1 2
8 6 7 1 2 None
"""

四、Python数据类型:整型、浮点型、复数、布尔、空值、字符串

4.1、整型int() :将指定进制(默认十进制)的一个字符串或数字(向下取整)转换为十进制整型(强转)。

import math

  • 向上取整:math.ceil(5.1) == 6
  • 向下取整:int(5.6) == 5math.floor(5.6) == 5
  • 四舍五入:round(5.6) == 6
"""#####################################################################
# 函数说明:int(x, base=10)
# 输入参数:
# 		x:		待要转换的值,支持字符串或数字
# 		base:	默认十进制。
#               若不输入参数base,表示将 (二进制、十进制、十六进制)的 x 转换为十进制。
# 				若输入参数base,则输入必须是整数,且整数必须以字符串格式输入。

# Python2 有 long int 类型,==而Python3 整型没有范围限制==,故可以当作 long int 使用。
# 布尔类型(bool)是整型的子类型,包括两种:True == 1、False == 0。
#####################################################################"""

# (1)将字符串转换为十进制整数
num_int = int("123")
print(num_int)              # Output: 123

# (2)将浮点数转换为整数
int_num = int(3.14)
print(int_num)              # Output: 3

# (3)将二进制字符串转换为十进制整数
decimal_int = int("1010", base=2)
print(decimal_int)          # Output: 10

# (4)将十六进制字符串转换为十进制整数
decimal_int = int("A5", base=16)
print(decimal_int)          # Output: 165

十进制转换为16进制

  • 十六进制范围:0 ~ 65536(0000 ~ FFFF)
  • 方法:
    • (1)十进制数除16(取余数1),得商1
    • (2)商1除16(取余数2),得商2
    • (3)商2除16(取余数3),得商3
    • (4)最后商3等于0(取余数4)
    • 最终结果为倒序余数= [余数4, 余数3, 余数2, 余数1]

举例(整数:65036)
(1)65036 除 16,商4064,余数 12(十六进制C)
(2)4064 除 16,商254,余数 0(十六进制0)
(3)254 除 16,商15,余数 14(十六进制E)
(4)15除16,商0,余数 15(十六进制F)
(5)结束:得16进制为 = FE0C

十进制0123456789101112131415
16进制0123456789ABCDEF
2进制0000000100100011010001010110011110001001101010111100110111101111

1、bin():十进制整数转换为二进制码。返回值为字符串。

函数说明:bin(整型)

print(bin(-3))
print(type(bin(-3)))

'''
-0b11
<class 'str'>
'''

2、ord(): ASCII字符转换为十进制整数(Unicode字符 —— Unicode数值)。

函数说明:ord(字符)

print(ord('A'))
print(type(ord('A')))

'''
65
<class 'int'>
'''

3、chr():将10进制或16进制数转换为ASCII字符。(Unicode数值 —— Unicode字符)。

函数说明:chr(number)

print(chr(97))
print(type(chr(97)))

'''
a
<class 'str'>
'''

4.2、浮点型float() :将数字、字符串或布尔值转化为浮点数(强转) —— 只支持十进制输入和输出。

函数说明:float(object)
输入参数:

  • object:整数、字符串、布尔值(若没有输入参数,则float=0.0
    备注1:当非十进制的字符串作为参数时,若超出数字字符时会报错。比如:float('2a1')
    备注2:不能进行不同进制之间的转换,否则系统报错。与int()完全不同。
print('空输入参数', float())
print('整数转换为浮点数', float(5))
print('浮点数转换为浮点数', float(-5.5))
print('字符串转换为浮点数', float('-5.5'))
print('布尔值转换为浮点数', float(True))

'''
空输入参数 0.0
整数转换为浮点数 5.0
浮点数转换为浮点数 -5.5
字符串转换为浮点数 -5.5
布尔值转换为浮点数 1.0
'''

4.3、复数complex():将数字、字符串或布尔值转化为复数类型(强转)。

复数由实数和虚数构成,其实部a和虚部b都是浮点型。返回值是复数类型。
函数说明:a + bjcomplex(a,b)

4.4、字符串str() :将参数转换成字符串类型(强转)—— 字符串是一个有序不可变序列。

函数说明:str(x, base=10)
一般来说,有序序列类型都支持索引,切片,相加,相乘,成员操作

print('返回空字符串:', str())
print('整数转换为字符串:', str(-23))
print('浮点数转换为字符串:', str(1.3e2))

print('返回空字符串:', type(str()))
print('整数转换为字符串:', type(str(-23)))
print('浮点数转换为字符串:', type(str(1.3e2)))

print('列表转换为字符串:', str([12, '-23.1', 'Python']))
print('元组转换为字符串:', str((23, '9we', -8.5)))
print('字典转换为字符串:', str({'Huawei': 'China', 'Apple': 'USA'}))
print('集合转换为字符串:', str({'China', 'Japan', 'UK'}))

'''
返回空字符串: 
整数转换为字符串: -23
浮点数转换为字符串: 130.0

返回空字符串: <class 'str'>
整数转换为字符串: <class 'str'>
浮点数转换为字符串: <class 'str'>

列表转换为字符串: [12, '-23.1', 'Python']
元组转换为字符串: (23, '9we', -8.5)
字典转换为字符串: {'Huawei': 'China', 'Apple': 'USA'}
集合转换为字符串: {'China', 'UK', 'Japan'}
'''

【4.4.1、字符串的常用函数】

1.1、str.join():将序列(字符串、元组、列表、字典)中的元素以指定字符连接,并返回一个新的字符串。

函数说明:'Separator'.join(Sequence)
功能说明:以Separator为分隔符,对Sequence所有元素进行逐个分割,并返回一个新的字符串。
输入参数:

  • Separator:代表分隔符。 可以是单个字符(如:''、','、'.'、'-'、'*'等),也可以是字符串(如: 'abc')。
  • Sequence:代表要连接的元素序列。可以是字符串、元组、列表、字典。
    备注1:SeparatorSequence都只能是string型,不能是int型和float型,否则系统报错。
    备注2:字典的读取是随机的。
a1 = 'I Love China !'
print('字符串: ', ' '.join(a1))

a11 = 'I Love China !'
print('字符串: ', ''.join(a11))

a2 = ['I', 'Love', 'China', '!']
print('列表: ', ' '.join(a2))

a3 = ('I', 'Love', 'China', '!')
print('元祖: ', ' '.join(a3))

a4 = {'I': 1, 'Love': 2, 'China': 3, '!': 4}
print('字典: ', ' '.join(a4))

'''
字符串:  I   L o v e   C h i n a   !
字符串:  I Love China !
列表:  I Love China !
元祖:  I Love China !
字典:  I Love China !
'''
import os     	# 导入路径模块
os.getcwd()   	# 获取当前路径
data_save = os.path.join(os.getcwd(), 'data_save')  # 获取当前路径并组合新的路径
print(data_save)

1.2、str.split():通过指定分隔符(默认为空格)对字符串进行切片,并返回分割后的字符串列表(list)。

函数说明:str.split(str=".", num=string.count(str))[n]
参数说明:

  • str: 表示分隔符,默认为空格,但是不能为空。若字符串中没有分隔符,则把整个字符串作为列表的一个元素。
  • num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量。
  • [n]: 表示选取第n个切片。
    • 注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略。
s = 'www.dod.com.cn'
print('分隔符(默认): ', s.split())                    # 【输出结果】分隔符(默认):  ['www.dod.com.cn']
print('分隔符(.): ', s.split('.'))                   # 【输出结果】分隔符(.):  ['www', 'dod', 'com', 'cn']
print('分割1次, 分隔符(.): ', s.split('.', 1))        # 【输出结果】分割1次, 分隔符(.):  ['www', 'dod.com.cn']
print('分割2次, 分隔符(.): ', s.split('.', 2))        # 【输出结果】分割2次, 分隔符(.):  ['www', 'dod', 'com.cn']
print('分割2次, 分隔符(.), 取出分割后下标为1的字符串: ', s.split('.', 2)[1])      # 【输出结果】分割2次, 分隔符(.), 取出分割后下标为1的字符串:  dod
print(s.split('.', -1))                             # 【输出结果】['www', 'dod', 'com', 'cn']
###########################################
# 分割2次, 并分别保存到三个变量
s1, s2, s3 = s.split('.', 2)
print('s1:', s1)                                    # 【输出结果】s1: www
print('s2:', s1)                                    # 【输出结果】s2: www
print('s3:', s2)                                    # 【输出结果】s3: dod
###########################################
# 连续多次分割
a = 'Hello<[www.dodo.com.cn]>Bye'
print(a.split('['))                                 # 【输出结果】['Hello<', 'www.dodo.com.cn]>Bye']
print(a.split('[')[1].split(']')[0])                # 【输出结果】www.dodo.com.cn
print(a.split('[')[1].split(']')[0].split('.'))     # 【输出结果】['www', 'dodo', 'com', 'cn']

1.3、str.count():统计字符串里某个字符出现的次数。可以选择字符串索引的起始位置和结束位置。

函数说明:str.count("char", start, end)str.count("char")
参数说明:

  • str:为要统计的字符(可以是单字符,也可以是多字符)。
  • start:为索引字符串的起始位置,默认参数为0。
  • end:为索引字符串的结束位置,默认参数为字符串长度即len(str)。
str_temp = "i love python, i am learning python"
print(str_temp.count("i"))              # 【输出结果】3           # 单字符统计:start和end为默认参数
print(str_temp.count("i", 2))           # 【输出结果】2           # 单字符统计:star=2,end值为默认参数
print(str_temp.count("i", 0, 5))        # 【输出结果】1           # 单字符统计:star=2,end=5
################################################################################################
print(str_temp.count("py"))             # 【输出结果】2           # 多字符统计:start和end为默认参数

1.4、str.strip():删除字符串(开头 / 结尾)指定字符(默认空格)或字符序列,但不能删除中间部分的字符。

函数说明:str3 = str1.strip(str2)
其中,str1是操作字符串,str2是待移除指定的字符或字符序列。str3是移除后生成的新字符串。

str_temp1 = "  123 ABCDEFG 321  "
str_temp2 = "123 ABCDEFG 321  "
str_temp3 = "123 ABCDEFG 321  "
print(str_temp1.strip())            # 【输出结果】"123 ABCDEFG 321"
print(str_temp2.strip('12'))        # 【输出结果】"3 ABCDEFG 321  "
print(str_temp3.strip('3'))         # 【输出结果】"123 ABCDEFG 321  "

1.5、str.lstrip():删除字符串左边指定字符(默认空格)。

txt_temp1 = "_hello_world_"
print(txt_temp1.rstrip('_'))        # 【输出结果】"_hello_world"

1.6、str.rstrip():删除字符串右边指定字符(默认空格)。

txt_temp2 = "  _hello_world_  "
print(txt_temp2.rstrip(' '))        # 【输出结果】"  _hello_world_"

1.7、str.upper():将字符串中所有小写字母转换为大写字母。若存在非字母字符,则正常显示。

str_temp = "I LOVE python"
print(str_temp.upper())         # 【输出结果】I LOVE PYTHON

1.8、str.lower():将字符串中所有大写字母转换为小写字母。若存在非字母字符,则正常显示。

str_temp = "I LOVE python"
print(str_temp.lower())         # 【输出结果】i love python

1.9、str.title():将字符串中所有英文单词的首字母转换为大写,其余转字母换为小写。若存在非字母字符,则正常显示。

str_temp = "I LOVE python"
print(str_temp.title())         # 【输出结果】I Love Python

1.10、str.ljust():左对齐文本。向指定字符串的右侧填充指定字符。

函数说明:str.ljust(width, fillchar)
输入参数:

  • str:表示要进行填充的字符串;
  • width:表示包括 str 本身长度在内,字符串要占的总长度;
  • fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'www.baidu.com'
addr = 'http://www.baidu.com'
print(S.ljust(35,'-'))			# 【输出结果】www.baidu.com--------------------
print(addr.ljust(35,'-'))		# 【输出结果】http://www.baidu.com-------------

1.11、str.rjust():右对齐文本。向指定字符串的左侧填充指定字符。

函数说明:str.rjust(width, fillchar)
输入参数:

  • str:表示要进行填充的字符串;
  • width:表示包括 str 本身长度在内,字符串要占的总长度;
  • fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'http://www.baidu.com/python'
addr = 'http://www.baidu.com'
print(S.rjust(35,'-'))			# 【输出结果】-----http://www.baidu.com/python
print(addr.rjust(35,'-'))		# 【输出结果】------------http://www.baidu.com

1.12、str.center():居中对齐文本。

函数说明:str.center(width, fillchar)
输入参数:

  • str:表示要进行填充的字符串;
  • width:表示包括 str 本身长度在内,字符串要占的总长度;
  • fillchar:指定填充字符串时所用的字符,默认情况使用空格(可选参数)。
S = 'http://www.baidu.com/python/'
addr = 'http://www.baidu.com'
print(S.center(35, '-'))			# 【输出结果】----http://www.baidu.com/python/---
print(addr.center(35, '-'))			# 【输出结果】--------http://www.baidu.com-------

1.13、str.find():查找字符串中,指定子串在指定范围内第一次出现的位置。若无,则返回-1。

函数说明:str.find(sub, start, end)
输入参数:

  • sub:指定的子串
  • start:索引的起始位置。默认值为0。
  • end:索引的结束位置。默认值为字符串长度len(str)。
str1 = '123xyzzaraabc'
print(str1.find('z'))  	# 结果 5

1.14、str.rfind():查找字符串中,指定子串在指定范围内最后一次出现的位置。若无,则返回-1。

函数说明:str.find(sub, start, end)
输入参数:

  • sub:指定的子串
  • start:索引的起始位置。默认值为0。
  • end:索引的结束位置。默认值为字符串长度len(str)。
str1 = '123xyzzaraabc'
print(str1.rfind('z'))  	# 结果 6

1.15、str.index():检测指定范围内的字符串中是否包含子串。若无,则系统报错。

函数说明:str.index(sub, start, end)
输入参数:

  • sub:指定的子串
  • start:索引的起始位置。默认值为0。
  • end:索引的结束位置。默认值为字符串长度len(str)。
A = '123xyzzaraabc'
print(A.index('xyz'))  	# 结果 3
print(A.index('zzz'))  	# 报错 :ValueError: substring not found

1.16、str.replace():将指定字符或子串替换为另一种字符。原字符串不改变。

函数说明:str.replace('old_str', 'new_str', count)
输入参数:

  • old_str:指定待替换的字符或子串
  • new_str:替换的字符或子串
  • count:替换的次数,默认全部替换。
    备注:当查看字符串时,发现原字符串并没有发生改变,说明str.replace()函数并不对原有的字符串进行改变。
str1 = '1112 QQQ QQQ 444 QQQ'
str1.replace('1', '5')				# 不改变原字符串		
print(str1)

str2 = str1.replace('1', '5')		# 默认全部替换
print(str2)

str3 = str1.replace('Q', 'g', 7)	# 指定替换次数
print(str3)

'''
1112 QQQ QQQ 444 QQQ
5552 QQQ QQQ 444 QQQ
1112 ggg ggg 444 gQQ
'''

1.17、str.endswith():判断字符串中(可指定范围)是否以指定字符或子串结尾。返回bool值。

函数说明:str.endswith(suffix, start, end)
输入参数:

  • suffix:后缀。可以是字符、字符串、元组(常用于判断文件类型)。
  • start:索引字符串的起始位置。默认0。
  • end:索引字符串的结束位置。默认字符串的长度。

备注:空字符的情况。返回值通常为True。

str = "i love python"
print("1:",str.endswith("")) 			# 空字符
print("2:",str.endswith("n")) 
print("3:",str.endswith("python"))
print("4:",str.endswith("n",0, 6))		# 索引 'i love' 是否以 'n' 结尾。
print("5:",str.endswith(("n","z")))		# 遍历元组,任意一个满足条件即返回True
print("6:",str.endswith(("k","m")))		# 遍历元组,任意一个满足条件即返回True
 
# 判断文件类型
file = "python.txt"
if file.endswith("txt"):					# 字符串类型
    print("该文件为文本。")
elif file.endswith(("AVI","WMV","RM")):		# 元祖类型
    print("该文件为视频。")
else:
    print("文件格式未知。")

'''
1: True
2: True
3: True
4: False
5: True
6: False
该文件为文本。
'''

【4.4.2、字符串的判断函数】

1.1、str.isdigit(),str.isnumeric(),str.isdecimal():检查字符串是否只包含十进制数字,返回布尔值。

中文汉字和英文数字的unicode编码范围

方法Unicode数字全角数字(双字节)罗马数字汉字数字byte数字(单字节)浮点数负数科学计数法二进制八进制十六进制
isdecimal()TrueTrueFalseFalseErrorFalseFalseFalseFalseFalseFalse
isdigit()TrueTrueFalseFalseTrueFalseFalseFalseFalseFalseFalse
isnumeric()TrueTrueTrueTrueErrorFalseFalseFalseFalseFalseFalse
str = '123'
print(str.isdecimal())  	
print(str.isdigit())  	
print(str.isnumeric())  

'''
True
True
True
'''

1.2、str.isupper(),str.islower(),str.istitle():检测字符串的大小写,返回布尔值。

  • (1)str.isupper():判断字符串中,含有字母的部分是否全大写。
  • (2)str.islower():判断字符串中,含有字母的部分是否全小写。
  • (3)str.istitle():检测字符串中,所有单词拼写的首字母是否为大写,且其他字母为小写。
str = '123aaa'
print(str.islower())  	
print(str.isupper())  	

str = 'This Is All'
print(str.istitle())  
str = 'This Is ALL'
print(str.istitle())  

'''
True
False
True
False
'''

1.3、str.isalpha():检测字符串是否只有字母,返回布尔值。

str = '12 aaAA'
print(str.isalpha())  	

str = ' aaAA'
print(str.isalpha())  
	
str = 'aaAA'
print(str.isalpha())  	

'''
False
False
True
'''

1.4、str.isalnum():检测字符串是否只有字母和数字,返回布尔值。

str = '12aaAA'
print(str.isalnum())  	

str = '12aa AA'
print(str.isalnum())  

'''
True
False
'''

1.5、str.isspace():判断字符串中是否只有空白字符(可以有多个空白字符),返回布尔值。

str = ' 123aaa'
print(str.isspace())  	

str = ' '
print(str.isspace())  
	
str = '   '
print(str.isspace())  	

'''
False
True
True
'''

五、Python函数

Python3 内置函数(大全)

5.1、高阶函数:sorted + map + filter + reduce + lambda + enumerate + zip + iter + next

3.1、sorted():对所有可迭代类型进行排序,不改变原始序列 —— 按照ASCII的大小进行排序(数字 >> 大写字母 >> 小写字母)。

函数说明:sorted(iterable, key=None, reverse=False)
输入参数:

  • iterable:可迭代的对象(如:字典、列表)。
  • key:可迭代类型中某个属性,对指定函数进行排序。默认=None
  • reverse默认升序(reverse=False)、降序(reverse=Ture)。

备注:字符串按照ASCII的大小进行排序。默认先排序数字(0 ~ 9),再排序大写字母(A ~ Z),后排序小写字母(a ~ z)。

lst1 = (5, 4, 3, -2, 1)
L1 = sorted(lst1)                       
L2 = sorted(lst1, key=abs)              
L3 = sorted(lst1, reverse=True)         
print(L1)			# 【输出结果】[-2, 1, 3, 4, 5]
print(L2)			# 【输出结果】[1, -2, 3, 4, 5]				
print(L3)			# 【输出结果】[5, 4, 3, 1, -2]
###################################################################################
lst2 = ('F', 'D', 'Y', 'e', 'a', 'v', '9', '6')
L4 = sorted(lst2)                       
L5 = sorted(lst2, key=str.lower)		# 对指定函数进行排序(将所有字母转换为小写,然后排序。不改变原字符串。)
print(L4)			# 【输出结果】['6', '9', 'D', 'F', 'Y', 'a', 'e', 'v']
print(L5)			# 【输出结果】['6', '9', 'e', 'F', 'v', 'Y']

3.2、map():将指定函数依次作用于序列中的每一个元素 —— 返回一个迭代器,结果需指定数据结构进行转换后输出。

函数说明:map(function, iterable)
输入参数:

  • function:指定函数。
  • iterable:可迭代对象
print('返回一个迭代器: ', map(int, (1, 2, 3)))
# 返回一个迭代器:  <map object at 0x0000018507A34130>

结果需指定数据结构进行转换后输出

  • 数据结构:list、tuple、set。可转换后输出结果
  • 数据结构:str。返回一个迭代器
  • 数据结构:dict。ValueError,需输入两个参数
print('将元组转换为list: ', list(map(int, (1, 2, 3))))
print('将字符串转换为list: ', tuple(map(int, '1234')))
print('将字典中的key转换为list: ', set(map(int, {1: 2, 2: 3, 3: 4})))

'''
将元组转换为list:  [1, 2, 3]
将字符串转换为list:  (1, 2, 3)
将字典中的key转换为list:  {1, 2, 3}
'''

################################################################################
dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
print(list(map(lambda x : x['name'] == 'python', dict_a)))
print(dict(map(lambda x : x['name'] == 'python', dict_a)))

"""
[True, False]
TypeError: cannot convert dictionary update sequence element #0 to a sequence
"""

3.3、filter():过滤掉不符合条件的元素 —— 返回一个迭代器,结果需指定数据结构进行转换后输出。

函数说明:filter(function,iterable)
输入参数:

  • function:判断函数
  • iterable:可迭代对象

函数功能:将序列中的每个元素循环传递给判断函数,并返回结果为True的元素组合成的新列表。

print('返回一个迭代器: ', filter(lambda x: x, list_num))
# 返回一个迭代器:  <filter object at 0x000002144BFB3130>

结果需指定数据结构进行转换后输出

  • 数据结构:list、tuple、set。可转换后输出结果
  • 数据结构:str。返回一个迭代器
  • 数据结构:dict。需输入两个参数,否则系统报错:ValueError
list_num = [1, 2, 3, 0, 8, 0, 3]
print(list(filter(lambda x: x, list_num)))					# 过滤:数字0

list_word = ['a', 'B', 'c', 'd', 'E']
print(tuple(filter(lambda x: x.isupper(), list_word)))		# 过滤:小写字母
print(set(filter(lambda x: x.islower(), list_word)))		# 过滤:大写字母
"""
[1, 2, 3, 8, 3]
('B', 'E')
{'c', 'd', 'a'}
"""

################################################################################
dict_a = [{'name': 'python', 'points': 10}, {'name': 'java', 'points': 8}]
print(list(filter(lambda x : x['name'] == 'python', dict_a)))
print(dict(filter(lambda x : x['name'] == 'python', dict_a)))

"""
[{'name': 'python', 'points': 10}]
{'name': 'points'}
"""

3.4、reduce():取序列的前2个元素,执行指定函数,然后将结果与第3个元素继续传入函数,循环到最后一个元素 —— 返回一个数值。

reduce函数在python2中是个内置函数,但在python3中已被移到functools模块。

函数说明:reduce(function, iterable, initializer)
输入参数:

  • function:指定函数(输入为两个元素)
  • iterable:可迭代对象
  • initializer:初始参数(可选),即指定第一个元素的值,然后与序列的第一个元素执行指定函数。
# 常与匿名函数lambda同时使用
from functools import reduce

print(reduce(lambda x,y: x+y, [1,2,3]))
print(reduce(lambda x,y: x+y, [1,2,3], 10))					# 表达式:取和
print(reduce(lambda x,y: x if x < y else y, [1,2,3]))		# 表达式:取最小值

"""
6
16
1
"""

性能对比:reduce相较于for循环,结构更简洁,但运行速度更慢。

from functools import reduce
import time


def test_for(arr):
    out = arr[0]
    for i in arr[1:]:
        out += i
    return out


def test_reduce(arr):
    out = reduce(lambda x, y: x + y, arr)
    return out


a = [i for i in range(100000)]
t1 = time.perf_counter()		# 起始时间
print(test_for(a))

t2 = time.perf_counter()		# for循环运行时间
print(test_reduce(a))

t3 = time.perf_counter()		# reduce运行时间
print('for循环耗时:', (t2 - t1))
print('reduce耗时:', (t3 - t2))


"""
4999950000
4999950000

for循环耗时: 0.0089341
reduce循环耗时: 0.0122448
"""

3.5、匿名函数(lambda):对输入参数进行表达式计算

函数说明1:函数名 = lambda argument_list: expression
函数说明2:函数名 = lambda 参数: 表达式(更容易理解,固定语法)
输入参数:

  • lambda:Python关键字
  • argument_list:(输入)参数列表,即输入可以是多个参数。
  • expression:变量表达式。只能是单行,而def可以有多个。
  • 返回值:变量表达式的计算结果即为lambda函数的返回值。

特点1:匿名函数,即没有名字的函数。Python中的lambda
特点2:功能简单:只能单行expression决定了lambda函数不可能完成复杂的逻辑,甚至不需要专门的名字来说明。

❤️ 常用实例

a0 = lambda x: 1 if x > 10 else 0		# 判断输入参数的大小,大于取1,小于取0
a1 = lambda x, y: x*y					# 函数输入是x和y,输出是它们的积x*y
a2 = lambda : None						# 函数没有输入参数,输出是None
a3 = lambda *args: sum(args)			# 输入是任意个数的参数,输出是它们的和(隐性要求是输入参数必须能够进行加法运算)
a4 = lambda **kwargs: 1					# 输入是任意键值对参数,输出是1

print(a0(2))
print(a1(2, 3))
print(a2())
print(a3(2, 3, 4))
print(a4())

"""
0
6
None
9
1
"""

❤️ 四个用法

(1)将lambda函数赋值给一个变量,通过这个变量间接调用该lambda函数。

  • 如:add0 = lambda x, y: x+y,返回两个变量的和。与add(1,2)==3等效。

(2)将lambda函数赋值给其他函数,从而将其他函数用该lambda函数替换。

  • 如:time.sleep = lambda x: None。返回None,即调用标准库time中的sleep函数不执行。

(3)将lambda函数作为其他函数的返回值,返回给调用者。

  • 如:return lambda x, y: x+y,返回一个加法函数。此时lambda函数实际上是定义在某个函数内部的函数,称为嵌套函数或内部函数。

(4)将lambda函数作为参数传递给其他函数。如:sorted()、filter()、map()、reduce()。

  • 11、sorted():此时lambda函数用于对列表中所有元素进行排序

    • 如:sorted([1, 2, 3, 4, 5], key=lambda x: abs(3-x))
      将列表[1, 2, 3, 4, 5]中元素与3的距离,从小到大进行排序,其结果是列表:[3, 2, 4, 1, 5]。
  • 22、filter():此时lambda函数用于过滤列表元素

    • 如:list(filter(lambda x: x%3==0, [1, 2, 3]))
      将列表[1,2,3]中能够被3整除的元素过滤出来,其结果是列表:[3]。
  • 33、map():此时lambda函数用于对列表中每一个元素的共同操作

    • 如:list(map(lambda x: x+1, [1, 2, 3]))
      将列表[1, 2, 3]中的元素分别加1,其结果是列表:[2, 3, 4]。
  • 44、reduce():此时lambda函数用于列表中两两相邻元素的结合

    • from functools import reduce
    • reduce(lambda a, b: a+b, [1, 2, 3, 4])
      将列表[1, 2, 3, 4]中的元素,从左往右取出2个元素并执行指定函数,然后将输出结果与第3个元素传入指定函数,…,循环到最后一个元素。其结果是整型:10。
      备注:reduce函数原本在python2中也是个内置函数,不过在python3中被移到functools模块中。

3.6、枚举函数(enumerate):同时获取可迭代对象的索引和值 —— 与for循环一起使用。

函数说明:index, value = enumerate(iteration, start)
输入参数:

  • iteration:可迭代对象。
  • start:自定义起始索引值,可选参数,默认为0。
    备注:指定起始点,改变的只是可迭代对象中每个元素对应的索引的变化。即无论是否指定起始点,可迭代对象都是从第一个元素读取。

输出参数:

  • index:索引值。
  • value:可迭代对象中索引对应的元素值。
    特点1:匿名函数,即没有名字的函数。
list1 = [1,2,3,4,5,6]
for index, value in enumerate(list1):			# 默认起始点
    print(indx, value)
########################################
print('*'*10)
########################################
for indx, value in enumerate(list1, 2):			# 指定起始点
    print(indx, value)

"""
0 1
1 2
2 3
**********
5 1
6 2
7 3
"""

3.7、组合序列(zip):将多个可迭代对象的第 i 个元素组合在一起(压缩),得到一个元祖,最后输出N个元组 —— 返回一个迭代器,结果需指定数据结构进行转换后输出。

函数说明:res = zip(iterable_1, iterable_2,..., iterable_n)
输入参数:

  • iteration:n个可迭代对象。
  • res:返回一系列元组的迭代器,第 i 个元组包含各输入iterables的第 i 个元素。

解压缩:unzip(把组合序列进行反向分解) —— python没有unzip函数
函数说明:zip(*res)
输入参数:

  • *:表示解包运算符。
  • res:由zip()生成的结果。
# (1)不传递参数,返回空的迭代器
print('1:', zip())									# <zip object at 0x00000205F02A3480>
print('1:', list(zip()))							# []
######################################################################
# (2)传递一个参数,返回tuple的迭代器。
print('2:', list(zip([1, 2, 3])))					# [(1,), (2,), (3,)]
######################################################################
# (3)传递两个参数,返回tuple的迭代器。
a3 = ['a', 'c', 'b']
b3 = ['2', '1']
print('3:', list(zip(a3, b3)))						# [('a', '2'), ('c', '1')]
print('3:', dict(zip(a3, b3)))						# {'a': '2', 'c': '1'}
######################################################################
# 4.1、传递长度不等的参数(截取最短,删除冗余)
print('4:', list(zip(range(3), range(100))))		# [(0, 0), (1, 1), (2, 2)]

# 4.2、传递长度不等的参数,若想要以最长的进行迭代处理,缺少部分补None
import itertools as it
fruits = ['apple', 'banana', 'melon', 'strawberry']
prices = [10, 20, 30]
print(list(it.zip_longest(fruits, prices)))			# [('apple', 10), ('banana', 20), ('melon', 30), ('strawberry', None)]
######################################################################
# (5)并行排序(以第一个输入参数进行排序)
print('5:', sorted(list(zip(a3, b3))))				# [('a', '2'), ('c', '1')]
print('5:', sorted(list(zip(b3, a3))))				# [('1', 'c'), ('2', 'a')]
######################################################################
# (6)解压缩序列:解包运算符*。
result = zip(a3, b3)
origin = list(zip(*result))		# 创建两个不同的元祖(数字和字母)
print('6:', origin[0])								# ('a', 'c')
print('6:', origin[1])								# ('2', '1')
######################################################################
# (7)将数据成对进行计算
total_sales = [52000.00, 51000.00, 48000.00]
prod_cost = [46800.00, 45900.00, 43200.00]
for sales, costs in zip(total_sales, prod_cost):
	profit = sales - costs
	print(f'Total profit: {profit}')
	
"""
Total profit: 5200.0
Total profit: 5100.0
Total profit: 4800.0
"""

3.8、iter():输入一个可迭代对象,将其转换成一个迭代器 —— 与 next() 一起使用。

"""#################################################
# 函数说明:iter(object, sentinel)
# 输入参数:
#       object:可迭代对象,但不一定可调用。若传入 sentinel 则必须是可调用对象。
#       sentinel(哨符, 又叫标记符):(可选参数) 当枚举值等于sentinel时,则自动停止。且不会输出sentinel值。
# 输出参数:
#       返回迭代器对象
#################################################"""

a_iter = iter([1, 2])
print(a_iter)			# <list_iterator object at 0x00000259E484A340>
print(next(a_iter))		# 1
print(next(a_iter))		# 2
print(next(a_iter))		# 迭代器耗尽,未指定默认值,提示 StopIteration 异常

"""
<list_iterator object at 0x0000026115492340>
1
2

Traceback (most recent call last):
  File "F:\py\main222.py", line 14, in <module>
    print(next(a_iter))		# 迭代器耗尽,未指定默认值,提示 StopIteration 异常
StopIteration
"""

3.9、next():检索迭代器的下一个元素 —— 与 iter()、yield() 一起使用

"""#################################################
# 函数说明:next(iterator, default)
# 输入参数:
#       iteration:        迭代器(不是可迭代对象,可迭代对象不是迭代器)
#       default(可选):    如果迭代器耗尽则返回此默认值。
#                   若没有给定默认值,则抛出 StopIteration 异常。
# 输出参数:
#       返回下一个元素
#################################################"""
it = iter([1, 2])
print(next(it))		# 1
print(next(it))		# 2
print(next(it))		# 迭代器耗尽,未指定默认值,提示StopIteration 异常。
print(next(it, 5))  # 5

"""
Traceback (most recent call last):
  File "F:\py\main222.py", line 13, in <module>
    print(next(it))		# 迭代器耗尽,未指定默认值,提示StopIteration 异常。
StopIteration

1
2
"""
######################################################################
it = iter([1, 3, 5])
try:
    while True:
        x = next(it)
        print(x, end=" ")
except StopIteration:  # 遇到StopIteration就退出循环
    print("raise StopIteration!")
"""
1 3 5 raise StopIteration!
"""

5.2、通用函数

1、input():获取控制台(任意形式)的输入,输出为字符串。

str1 = input()

print(str1)
print('打印字符串:', str1)
print('字符串类型:', type(str1))

'''
as&d123#
打印字符串: as&d123#
字符串类型:<class 'str'>
'''

  1.1、int(input()) 与 map(int, input().spilt()) 的区别

常用的强转类型说明
int(input())强转为整型(int类型只能输入一个整数字符串
map(int, input().spilt())强转为整型(map函数可以输入多个整数字符串
list(input())强转为列表(输入可以是任意类型)

  1.2、input() 与 list(input()) 的区别、及其相互转换方法

  • 相同点:两个方法都可以进行for循环迭代提取字符,提取后都为字符串类型。
  • 不同点str = list(input()) 将输入字符串转换为list类型,可以进行相关操作。如: str.append()
  • 将列表转换为字符串:str_list = ['A', 'aA', 2.0, '', 1]
  • 方法一:print(''.join(str))
  • 方法二:print(''.join(map(str, str_list)))

备注:若list中包含数字,则不能直接转化成字符串,否则系统报错。

  • 方法一:print(''.join([str(ii) for ii in str_list]))
  • 方法二:print(''.join(map(str, str_list)))
    map():根据给定函数对指定序列进行映射。即把传入函数依次作用到序列的每一个元素,并返回新的序列。

(1) 举例说明:若list中包含数字,则不能直接转化成字符串,否则系统报错。

str = ['25', 'd', 19, 10]
print(' '.join(str))

'''
Traceback (most recent call last):
 File "C:/Users/Administrator/Desktop/test.py", line 188, in <module>
   print(' '.join(str))
TypeError: sequence item 3: expected str instance, int found
'''

(2)举例说明:若list中包含数字,将list中的所有元素转换为字符串。

str_list = ['A', 'aA', 2.0, '', 1]
print(''.join(str(ii) for ii in str_list))
print(''.join([str(ii) for ii in str_list]))
print(''.join(map(str, str_list))) 		# map():根据给定函数对指定序列进行映射。即把传入函数依次作用到序列的每一个元素,并返回新的序列。

'''
AaA2.01
AaA2.01
AaA2.01
'''

2、print() :用于打印输出

【Python】print()函数的用法

x, y = 1, 9

print('{}, {}' .format(x, y))   # 打印方法一
print(x, ',', y)				# 打印方法二
print('*'*10)					# 打印分割符

'''
1, 9
1 , 9
**********
'''

3、range() :输出指定范围内的所有值(前闭后开)

"""#################################################
# 函数说明:range(start=0,stop,step=1)
# 输入参数:
#         start(可选):    序列的起始点(默认0)
#         stop:           序列的终止点
#         step(可选):     滑动步长(默认1)
#                   (1)正数表示迭代上升
#                   (2)负数表示迭代下降
#
# 备注:前闭后开[A,B),即能取到A值,但取不到B值。
#################################################"""
# (1)指定stop=3, start默认为0,step默认为1
for i in range(3):
    print('A =', i)

# (2)指定start=2, stop=3, step默认为1
for i in range(2, 3):
    print('B =', i)

# (3)指定start=5, stop=2, step=-2
for i in range(5, 2, -2):
    print('C =', i)
'''
A = 0
A = 1
A = 2

B = 2

C = 5
C = 3
'''

4、len():返回可迭代对象的长度(字符串、列表、字典、元组等)

"""#################################################
# 函数说明:len(iter_object)
# 输入参数:可迭代对象
# 输出参数:可迭代对象的长度(即:参数的个数)
#################################################"""

str_temp = "Hello, boy !"
print(len(str_temp))                    # 【输出结果】12
#############################################
list_temp = ['h', 'e', 'l', 'l', 'o']
print(len(list_temp))                   # 【输出结果】5
#############################################
dict_temp = {'num': 520, 'name': "do do"}
print(len(dict_temp))                   # 【输出结果】2
#############################################
tuple_temp = ('G', 'o', 'o', 'd')
print(len(tuple_temp))                  # 【输出结果】4

5、eval():返回表达式的值 —— 输入可以是任意类型,输出与输入类型一致

"""#################################################
# 函数说明:eval(expression, globals, locals)
# 输入参数:
#         expression:   字符串表达式。输入可以是任意类型。
#         globals:      变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
#         locals:       变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
#
#         优先级:locals > globals > expression。若三个参数有相同的变量,则按照优先级进行赋值。
#################################################"""

print(type(eval('1')))
print(type(eval('1.0')))
print(type(eval("'1'")))
print(type(eval('{1}')))
print(type(eval('[1,2]')))
print(type(eval('{2:2}')))
print(type(eval('(1,2)')))

"""
<class 'int'>
<class 'float'>
<class 'str'>
<class 'set'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
"""
##########################
# (1)expression参数示例
a1 = 10
temp1 = eval("a1+1")			# a1=10
print(temp1)
print(type(temp1))
##########################
# (2)globals参数示例
a2 = 10
g = {'a2': 4}
temp2 = eval("a2+1", g)			# a2=4
print(temp2)
print(type(temp2))
##########################
# (3)locals参数示例
a3 = 10
b3 = 20
c3 = 30
g = {'a3': 6, 'b3': 8}
t = {'b3': 100, 'c3': 10}
temp3 = eval("a3+b3+c3", g, t)	# a3=6、b3=100、c3=10
print(temp3)
print(type(temp3))
##########################
"""
11
<class 'int'>
5
<class 'int'>
116
<class 'int'>
"""

5.3、数学函数 + 随机数函数 + 三角函数 + 数学常量

Python标准库:import math(常量 + 数学函数 + 幂与对数 + 三角函数)

1、数学函数

在这里插入图片描述

  1.1、round():四舍五入 —— 支持保留小数点的指定位数

"""#################################################
# 函数功能:四舍五入
# 函数说明:round(x, n)
# 输入参数:
#       x:浮点数或整数。若为整数,则n无效,直接输出整数。
#       n:保留小数点的位数。
#################################################"""
# 四舍五入规则:
#       (1)若保留位数的后一位 <=4,则不进位。                   如:round(5.214, 2)     结果为5.21。
#       (2)若保留位数的后一位 =5,且该位数后面没有数字,则不进位。   如:round(5.215, 2)     结果为5.21。
#       (3)若保留位数的后一位 =5,且该位数后面有数字,则进位。      如:round(5.2151, 2)    结果为5.22。
#       (4)若保留位数的后一位 >=6,则进位。                     如:round(5.216,2)      结果为5.22。

print(round(5, 2))			# 5				# 整数
print(round(5.214, 2))		# 5.21			# <=4,则不进位
print(round(5.215, 2))		# 5.21			# =5,且该位数后面没有数字,则不进位
print(round(5.2151, 2))		# 5.22			# =5,且该位数后面有数字,则进位
print(round(5.216, 2))		# 5.22			# >=6,则进位

  1.2、sum():求和

"""#################################################
# 函数说明:sum(iterable, start)
# 输入参数:
#       iterable:   可迭代对象(如:列表 + 元组 + 集合 + 字典 + 字符串)
#       start:      指定相加的参数,默认为0。
#################################################"""

print(sum([1, 2, 3]))			# 6
print(sum((1, 2, 3)))			# 6
print(sum({1, 2, 3}))			# 6
print(sum(range(5)))			# 10
##########################
print(sum([1, 2, 3], 2))		# 8
print(sum((1, 2, 3), 2))		# 8
print(sum({1, 2, 3}, 2))		# 8
print(sum(range(5), 2))			# 12

  1.3、abs() + fabs():返回绝对值

abs()fabs()
abs()是python的内置函数fabs()是math模块中的函数(import math)
适用范围float、int、complexfloat、int
1若输入为整型,则返回整型;若输入为整型,则自动保留一个小数。
2若输入为浮点型或复数类型,则返回浮点型。若输入为浮点型,则返回浮点型
import math

# 输入整型
print(abs(10))						# 10
print(math.fabs(10))				# 10.0

# 输入浮点型
print(abs(10.125))					# 10.125
print(math.fabs(10.125))			# 10.125

# 输入复数类型
print(abs(10.125+12j))				# 15.62850460696736
# print(math.fabs(10.125+12j))		# TypeError: can't convert complex to float

  1.4、开根号(四种方法)

# 方法1:数字**0.5

x = int(input('数字:'))**0.5         	# 数字:50
print(x)                                # 7.0710678118654755
print(type(x))                          # <class 'float'>
###############################################################
# 方法2:pow(数字,次方)

x = pow(int(input('数字:')), 0.5)        # 数字:50
print(x)                                # 7.0710678118654755
print(type(x))                          # <class 'float'>
###############################################################
# 方法3:math.sqrt(数字)

import math
x = math.sqrt(int(input('数字:')))      # 数字:50
print(x)                                # 7.0710678118654755
print(type(x)) 	                        # <class 'float'>
###############################################################
# 方法4:cmath.sqrt(数字)

import cmath
x = cmath.sqrt(int(input('数字:')))     # 数字:50
print(x)                                # (7.0710678118654755+0j)
print(type(x))                          # <class 'complex'>

2、随机数函数

在这里插入图片描述

3、三角函数

在这里插入图片描述

4、数字常量

在这里插入图片描述


文献参考

1.【Python3】内置函数(大全)
2.【Python3】字符串常用方法(大全)
3.【Python】encode()函数
4.【Python】decode()与encode()详解
5.【Python】字符串isdecimal() isdigit()isnumeric()等判断方法的区分。
6.TypeError: sequence item 0: expected str instance, int found的解决办法

  • 28
    点赞
  • 153
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胖墩会武术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值