Hãy giải quyết vấn đề này. Câu lệnh
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
4 không phải là câu lệnh def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
3 như bạn có thể quen thuộc trong C, C++, C# và nhiều ngôn ngữ khác. Bạn có thể sử dụng nó như một câu lệnh chuyển đổi, nhưng thu được rất ít so với một loạt câu lệnh def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
6Câu lệnh khớp trong Python là một câu lệnh khớp mẫu với cú pháp của các biểu thức con cho
- Phù hợp với hình dạng của một chuỗi
- Các mục phù hợp trong một chuỗi
- Khớp các khóa và giá trị trong từ điển
- Khớp các giá trị bằng chữ
Bạn có thể kết hợp một hoặc nhiều trong số này thành một câu lệnh để lọc dữ liệu dựa trên đầu vào. Điều này được gọi là "khớp mẫu cấu trúc" và đó là một tính năng của nhiều ngôn ngữ lập trình chức năng
Kết hợp mẫu trình tự
Câu lệnh khớp có một cú pháp đặc biệt để khớp các chuỗi. Cú pháp sử dụng dấu ngoặc vuông
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
7, nhưng nó sẽ khớp với bất kỳ loại def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
8 nào [tuple, list, bytearray]Bắt đầu với một cái gì đó đơn giản. Hàm này sẽ trả về true nếu đầu vào là một chuỗi bắt đầu bằng một chuỗi ký tự của một con ếch unicode
from typing import Sequence
def starts_with_frog[seq: Sequence[str]] -> bool:
""" Test matching the first element of a sequence is a frog. """
match seq:
case ["🐸", *_]: return True
case _: return False
print[starts_with_frog[["🐸", "🐛", "🦋", "🪲"]]] # True
print[starts_with_frog[["🐛", "🦋", "🪲"]]] # False
# Also works for tuples without modification
print[starts_with_frog[["🐸", "🐛", "🦋", "🪲"]]] # True
# You can throw all sorts of junk at the function without it crashing
print[starts_with_frog[None]] # False
print[starts_with_frog["ribbit"]] # False
print[starts_with_frog["🐸"]] # False
Mã Python tương đương sẽ được thể hiện dưới dạng
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
Vì vậy, những gì sẽ đạt được bằng cách sử dụng câu lệnh đối sánh? . Điều này là do biểu thức so khớp trình tự biên dịch thành các hướng dẫn hiệu quả hơn nhiều so với câu lệnh if được xâu chuỗi
Với câu lệnh đối sánh, các trường hợp được đánh giá theo thứ tự. Sử dụng điều này để đặt các trường hợp cụ thể ở trên cùng và sau đó trở nên chung chung hơn khi bạn đi xuống. Để khớp trình tự, bạn có thể sử dụng biểu thức ký tự đại diện
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
9 để khớp với from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
0 mụcBạn có thể sử dụng biểu thức
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
7 để khớp với một chuỗi trống và sau đó sử dụng from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
2 để khớp với bất kỳ chuỗi nào khác________số 8_______Ký tự đại diện
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
9 sử dụng tên biến tạm thời from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
4. Bạn có thể thay thế tên này bằng một tên để sử dụng biến đó trong khối trường hợpfrom typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
Bạn có thể sử dụng “mẫu phụ” trong khớp nối tự để khớp các trường hợp khác nhau trong bất kỳ mục nào. Sử dụng dấu ngoặc đơn để đánh dấu một nhóm và toán tử đường ống
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
5 để biểu thị và mệnh đề “hoặc”from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", ["🌹" | "🌸" | "🌺" | "🌻" | "🌼"]]: return f"A frog and a flower"
case _: return "Not sure"
khớp chữ
Các câu lệnh tình huống có thể bao gồm bất kỳ chữ nào, như một chuỗi ký tự, một số, boolean,
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
6Cập nhật ví dụ để khớp với một chuỗi ký tự duy nhất với con ếch
from typing import Any
def describe[seq: Any] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case "🐸": return "A frog"
case _: return "No idea"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
print[describe["🐸"]] # A frog
So khớp theo nghĩa đen là gần nhất với câu lệnh
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
3, nhưng như chúng ta đã đề cập ở phần đầu, bạn có thể kết hợp nó với bất kỳ biểu thức khớp mẫu nào khácKết hợp theo nghĩa đen cũng có thể bao gồm toán tử đường ống
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
5 hoặc biểu thị biểu thức from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
9def describe[seq] -> str:
match seq:
case ["🐸", *others]: return f"A frog and {others}"
case "🐸" | "🤴": return "A frog or a prince?"
case "👸": return "A princess"
case "😘": return "A kiss"
case _: return "Not sure"
print[describe["🐸"]] # A frog or a prince?
print[describe["🤴"]] # A frog or a prince?
print[describe["😘"]] # A kiss
print[describe[None]] # Not sure
Để hoàn thành chức năng này, hãy thay thế trường hợp chuỗi bằng một lệnh gọi đệ quy để mô tả từng phần tử trong chuỗi
def describe[seq] -> str:
match seq:
case [*others]: return ", ".join[describe[other] for other in others]
case "🐸" | "🤴": return "A frog or a prince?"
case "👸": return "A princess"
case "😘": return "A kiss"
case _: return "Not sure"
print[describe["🐸"]] # A frog or a prince?
print[describe[["🐸", "👸", "😘", "🤴"]]] # A frog or a prince?, A princess, A kiss, A frog or a prince?
ánh xạ phù hợp
Câu lệnh khớp có cú pháp khớp các khóa và giá trị trong các loại ánh xạ [từ điển và các lớp con của từ điển]
Giả sử bạn có một API lấy dữ liệu JSON bán cấu trúc làm đầu vào
{
"name": "Charles Leclerc",
"team": "Ferrari",
"height": 179
}
Dữ liệu JSON sau đó được giải tuần tự hóa bằng cách sử dụng
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
0, nhưng bạn cần phải phục vụ cho một số tình huống- Người dùng không bao gồm trường
1, vì vậy chúng tôi cần tra cứu trường nàyfrom typing import Sequence def describe[seq: Sequence[str]] -> str: match seq: case ["🐸", *others]: return f"Starts with frog and ends with {others}" case _: return "Not sure" print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
- Người dùng không bao gồm trường
2, vì vậy chúng tôi cần tra cứu trường nàyfrom typing import Sequence def describe[seq: Sequence[str]] -> str: match seq: case ["🐸", *others]: return f"Starts with frog and ends with {others}" case _: return "Not sure" print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
- Người dùng không gửi các trường bắt buộc
Bạn có thể thể hiện các khớp ánh xạ bằng cách sử dụng dấu ngoặc nhọn
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
3 và sau đó một hoặc nhiều khóa bạn muốn khớp bằng các ký tự. Sau đó, bạn có thể sử dụng các biểu thức được đặt tên hoặc tên tạm thời from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *_, "🦋", "🌼"]: return "Starts with frog and ends with a flower, with a butterfly in between"
case ["🐸", *_, "🦋"]: return "Starts with frog and ends with a butterfly"
case [*_, "🦋"]: return "Ends with a butterfly"
case ["🐸", *_, "🌼"]: return "Starts with frog"
case ["🐸", *_]: return "Starts with frog"
case []: return "An empty sequence"
case [*_]: return "A sequence of things"
case _: return "Not a sequence"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog
print[describe[["🐸", "🦋"]]] # Starts with frog and ends with a butterfly
print[describe[["🐸", "🦋", "🌼"]]] # Starts with frog and ends with a flower, with a butterfly in between
print[describe[None]] # Not a sequence
4 để thu thập dữ liệu đó cho khối trường hợpdef add_driver[driver]:
match driver:
case {"name": name, "team": team, "height": height}: insert_driver_record[name, team, height]
case {"name": name, "height": height}: insert_driver_record[name, lookup_team[name], height]
case {"name": name}: insert_driver_record[name, lookup_team[name], lookup_height[height]]
case _: raise ValueError["Invalid request. Missing required fields"]
Điều quan trọng, đối sánh ánh xạ sẽ kiểm tra sự tồn tại của các khóa bất kể dữ liệu nào khác có trong từ điển
Nếu bạn muốn nắm bắt các khóa và giá trị khác, bạn có thể sử dụng biểu thức
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
5 với một biến được đặt têndef starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
0Đối tượng phù hợp
Cuối cùng, và có lẽ tính năng mạnh mẽ nhất của câu lệnh so khớp là so khớp đối tượng
Lấy cấu trúc lớp cơ bản này dựa trên API mà chúng ta vừa mô tả với các thuộc tính
from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
6, from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
1 và from typing import Sequence
def describe[seq: Sequence[str]] -> str:
match seq:
case ["🐸", *others]: return f"Starts with frog and ends with {others}"
case _: return "Not sure"
print[describe[["🐸", "🐸", "🐸"]]] # Starts with frog and ends with ['🐸', '🐸']
8def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
1Bạn có thể sử dụng đối sánh mẫu đối tượng để khớp các trường hợp thuộc tính của các lớp đó
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
2Phần kết luận
Tôi hy vọng điều này rất sâu sắc và bạn có thể thấy nơi bạn có thể thay thế các câu lệnh if lộn xộn, lồng nhau bằng các câu lệnh
def starts_with_frog[seq: Sequence[str]] -> bool:
if isinstance[seq, Sequence] and len[seq] > 0 and seq[0] == "🐸":
return True
return False
4 nhanh chóng và rõ ràng