match-case语句

Python 3.10 版本引入的新语法

用法如下:

1
2
3
4
5
6
7
match expression:
case pattern1:
# 处理pattern1的逻辑
case pattern2:
# 处理pattern2并且满足condition的逻辑
case _:
# 处理其他情况的逻辑
  • case _相当于C语言里面的default

  • 使用变量

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    def match_example(item):
    match item:
    case (x, y) if x == y:
    print(f"匹配到相等的元组: {item}")
    case (x, y):
    print(f"匹配到元组: {item}")
    case _:
    print("匹配到其他情况")

    match_example((1, 1)) # 输出: 匹配到相等的元组: (1, 1)
    match_example((1, 2)) # 输出: 匹配到元组: (1, 2)
    match_example("other") # 输出: 匹配到其他情况
  • 类型匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Circle:
def __init__(self, radius):
self.radius = radius

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height

def match_shape(shape):
match shape:
case Circle(radius=1):
print("匹配到半径为1的圆")
case Rectangle(width=1, height=2):
print("匹配到宽度为1,高度为2的矩形")
case _:
print("匹配到其他形状")

match_shape(Circle(radius=1)) # 输出: 匹配到半径为1的圆
match_shape(Rectangle(width=1, height=2)) # 输出: 匹配到宽度为1,高度为2的矩形
match_shape("other") # 输出: 匹配到其他形状

循环语句

  • Python中没有do-while循环

  • while后面可以跟else:

    如果while里面的东西,中途执行的时候发生错误,则不会执行else

    1
    2
    3
    4
    5
    6
    7
    8
    #!/usr/bin/python3

    count = 0
    while count < 5:
    print (count, " 小于 5")
    count = count + 1
    else:
    print (count, " 大于或等于 5")
  • for后面也可以跟else:

    如果for里面的东西,中途执行的时候发生错误,则不会执行else

    1
    2
    3
    4
    for x in range(6):
    print(x)
    else:
    print("Finally finished!")
  • Pythonbreakcontinue的用法同C语言。

  • pass语句:保持程序结构的完整性,一般用做占位语句

推导式

列表推导式

如下:

1
2
3
4
5
6
7
[表达式 for 变量 in 列表] 
[out_exp_res for out_exp in input_list]

或者

[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]

字典推导式

键后面跟冒号然后是值。

1
2
3
4
5
{ key_expr: value_expr for value in collection }



{ key_expr: value_expr for value in collection if condition }

如:

1
2
3
4
5
listdemo = ['Google','Runoob', 'Taobao']
# 将列表中各字符串值为键,各字符串的长度为值,组成键值对
>>> newdict = {key:len(key) for key in listdemo}
>>> newdict
{'Google': 6, 'Runoob': 6, 'Taobao': 6}

集合推导式

格式如下:

1
2
3
{ expression for item in Sequence }

{ expression for item in Sequence if conditional }

例程:

1
2
3
4
5
6
7
8
9
10
11
>>> setnew = {i**2 for i in (1,2,3)}
>>> setnew
{1, 4, 9}



>>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'d', 'r'}
>>> type(a)
<class 'set'>

元组推导式

使用方法如下:

1
2
3
(expression for item in Sequence )

(expression for item in Sequence if conditional )

例程:

1
2
3
4
5
6
>>> a = (x for x in range(1,10))
>>> a
<generator object <genexpr> at 0x7faf6ee20a50> # 返回的是生成器对象

>>> tuple(a) # 使用 tuple() 函数,可以直接将生成器对象转换成元组
(1, 2, 3, 4, 5, 6, 7, 8, 9)

迭代器

迭代器是一个可以记住遍历的位置的对象。

迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。

迭代器有两个基本的方法:iter()next()

字符串,列表或元组对象都可用于创建迭代器:

  • next输出迭代器

    1
    2
    3
    4
    5
    6
    7
    >>> list=[1,2,3,4]
    >>> it = iter(list) # 创建迭代器对象
    >>> print (next(it)) # 输出迭代器的下一个元素
    1
    >>> print (next(it))
    2
    >>>

    值得注意的是,如果遍历了所有的it对象(即输出了1,2,3,4),再使用next(it),会产生StopIteration报错。

    此时可以用下一个方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #!/usr/bin/python3

    import sys # 引入 sys 模块

    list=[1,2,3,4]
    it = iter(list) # 创建迭代器对象

    while True:
    try:
    print (next(it))
    except StopIteration:
    sys.exit()
  • for循环遍历迭代器对象

    1
    2
    3
    4
    5
    6
    #!/usr/bin/python3

    list=[1,2,3,4]
    it = iter(list) # 创建迭代器对象
    for x in it:
    print (x, end=" ")
  • 把一个类作为一个迭代器

    需要在类中实现两个方法 iter() 与 next() 。

    • __iter__()方法

      返回一个特殊的迭代器对象, 这个迭代器对象实现了 next() 方法并通过 StopIteration 异常标识迭代的完成。

    • __next__()方法

      会返回下一个迭代器对象

    • 例程:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      class MyNumbers:
      def __iter__(self):
      self.a = 1
      return self

      def __next__(self):
      x = self.a
      self.a += 1
      return x

      myclass = MyNumbers()
      myiter = iter(myclass)

      print(next(myiter))
      print(next(myiter))
      print(next(myiter))
      print(next(myiter))
      print(next(myiter))
      # 输出结果:
      # 1
      # 2
      # 3
      # 4
      # 5

生成器

在 Python 中,使用了 yield 的函数被称为生成器(generator)。

yield 是一个关键字,用于定义生成器函数,生成器函数是一种特殊的函数,可以在迭代过程中逐步产生值,而不是一次性返回所有结果。

当在生成器函数中使用 yield 语句时,函数的执行将会暂停,并将 yield 后面的表达式作为当前迭代的值返回。

然后,每次调用生成器的 next() 方法或使用 for 循环进行迭代时,函数会从上次暂停的地方继续执行,直到再次遇到 yield 语句。这样,生成器函数可以逐步产生值,而不需要一次性计算并返回所有结果。

调用一个生成器函数,返回的是一个迭代器对象。

例程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def countdown(n):
while n > 0:
yield n
n -= 1

# 创建生成器对象
generator = countdown(5)

# 通过迭代生成器获取值
print(next(generator)) # 输出: 5
print(next(generator)) # 输出: 4
print(next(generator)) # 输出: 3

# 使用 for 循环迭代生成器
for value in generator:
print(value) # 输出: 2 1

使用yeid实现斐波那契数列:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python3

import sys

def fibonacci(n): # 生成器函数 - 斐波那契
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f 是一个迭代器,由生成器返回生成

while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()
# 输出结果 ;0 1 1 2 3 5 8 13 21 34 55

参考资料