Python 是一门简洁而强大的编程语言,具备许多高级语法糖(syntactic sugar)功能,这些功能使得代码更易读、更简洁、更具可维护性
下面是常见的一些语法糖
列表推导式
def func1():
# 在一行代码中生成一个新的列表,而无需使用传统的for循环
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers)
def func2():
# 在列表推导式中添加条件,只包含满足条件的元素
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers)
def func3():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1:7:2])
if __name__ == "__main__":
func1()
func2()
func3()
字典推导式
def func1():
# 字典推导式可以以简洁的方式创建字典。可以使用一个表达式来定义字典的键和值。
words = ['hello', 'world', 'python', 'programming']
word_lengths = {word: len(word) for word in words}
print(word_lengths)
if __name__ == "__main__":
func1()
集合推导式
def func1():
# 用于快速去重或生成唯一的元素集合
numbers = [1, 2, 2, 3, 3, 4, 5, 5]
unique_numbers = {x for x in numbers}
print(unique_numbers)
if __name__ == "__main__":
func1()
生成器表达式
def func1():
# 生成器表达式是一种创建生成器的简洁方式,与列表推导式类似,但不会立即创建一个完整的列表。生成器逐个生成元素,这在处理大型数据集时非常有用,因为它们节省内存
numbers = [1, 2, 3, 4, 5]
squared_numbers = (x ** 2 for x in numbers)
print(squared_numbers)
# 输出: <generator object <genexpr> at 0x7f3bc5360510>
for n in squared_numbers:
print(n)
if __name__ == "__main__":
func1()
上下文管理器
def func1():
# 确保资源正确分配和释放的方式。使用 with 语句,可以在代码块内部安全地操作资源,如文件或数据库连接
with open('example.txt', 'r') as file:
data = file.read()
print(data)
# 在离开with块时,文件会自动关闭
if __name__ == "__main__":
func1()
自定义迭代器
class MyRange(object):
# 通过定义 __iter__() 和 __next__() 方法,可以创建自己的可迭代对象和迭代器
# 这可以使用 for 循环来遍历自定义数据结构
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
def func1():
my_range = MyRange(1, 5)
for num in my_range:
print(num)
if __name__ == "__main__":
func1()
多重赋值
def func1():
# 在一行中进行多个变量的赋值,这使得交换变量的值变得非常简单
a, b = 10, 20
a, b = b, a # 交换a和b的值
print(a, b)
if __name__ == "__main__":
func1()
带有else的循环
def func1():
# for 和 while 循环可以附带一个 else 块,它会在循环正常结束时执行,但如果循环被中断(例如,通过 break 语句),则不会执行。
for i in range(5):
print(i)
else:
print("循环正常结束")
print("-" * 20)
for i in range(5):
if i == 3:
break
print(i)
else:
print("循环正常结束")
if __name__ == "__main__":
func1()
使用enumerate获取索引
def func1():
# enumerate 函数用于同时获取迭代对象的索引和值,使得遍历列表等数据结构时更加方便。
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
if __name__ == "__main__":
func1()
使用zip组合迭代器
def func1():
# zip 函数可以将多个迭代器组合成一个元组序列,这使得同时迭代多个列表变得容易。
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"Name: {name}, Score: {score}")
if __name__ == "__main__":
func1()
装饰器
见文件夹装饰器
Union Operators: The Most Elegant Way To Merge Python Dictionaries(v3.9.0)
def func1():
# 合并多个字典
cities_us = {'New York City': 'US', 'Los Angeles': 'US'}
cities_uk = {'London': 'UK', 'Birmingham': 'UK'}
cities_jp = {'Tokyo': 'JP'}
cities = {}
for city_dict in [cities_us, cities_uk, cities_jp]:
for city, country in city_dict.items():
cities[city] = country
print(cities)
# 3.9.0以后
cities_us = {'New York City': 'US', 'Los Angeles': 'US'}
cities_uk = {'London': 'UK', 'Birmingham': 'UK'}
cities_jp = {'Tokyo': 'JP'}
cities = cities_us | cities_uk | cities_jp
print(cities)
cities_us = {'New York City': 'US', 'Los Angeles': 'US'}
cities_uk = {'London': 'UK', 'Birmingham': 'UK'}
cities_jp = {'Tokyo': 'JP'}
cities_us |= cities_uk | cities_jp
print(cities_us)
if __name__ == "__main__":
func1()
Type Hints: Make Your Python Programs Type Safe
from typing import Final
# 声明常量
DATABASE: Final = "MySQL"
# 声明字符,如果更换类型,IDE会高亮“Expected type 'str', got 'int' instead ”
name: str = "gudaxin"
name = 1
print(name)
F-Strings: A Pythonic String Formatting Approach
ellipsis
def write_an_article():
...
class Author:
...
write_an_article()
Author()
lambda
leaders = ["Warren Buffett", "Yang Zhou", "Tim Cook", "Elon Musk"]
leaders.sort(key=lambda x: len(x))
print(leaders)
三元运算
a = 1
b = 2
short_one = a if len(a) < len(b) else b
Walrus Operator
while (line := input()) != "stop":
print(line)
Continuous Comparisons
a = 4
if 1 < a < 10:
...
解构赋值技巧
person = {'name': 'Yang', 'age': 30, 'location': 'Mars'}
name, age, loc = person.values()
print(name, age, loc)
# Yang 30 Mars
person = {'name': 'Yang', 'age': 30, 'location': 'Mars'}
name, *others = person.values()
print(name, others)
# Yang [30, 'Mars']
用星号拆包可迭代对象
A = [1, 2, 3]
B = (4, 5, 6)
C = {7, 8, 9}
L = [*A, *B, *C]
print(L)
# [1, 2, 3, 4, 5, 6, 8, 9, 7]
Any() and All() Functions
适用于可迭代对象:list, tuple, or set
leaders = ['Yang', 'Elon', 'Sam', 'Tim']
starts_with_Y = any(name.startswith('Y') for name in leaders)
print(starts_with_Y)
# True
数字下划线
10_000_000_000 == 10000000000
评论区