Python 以其简洁、易读和优雅的语法而著称。以下是一些常用的优雅简洁的 Python 语法写法,掌握后可以很大的提升开发效率:
-
列表推导式 (List Comprehension)
python复制代码
# 常规写法 | |
numbers = [1, 2, 3, 4, 5] | |
squared = [] | |
for num in numbers: | |
squared.append(num ** 2) | |
# 列表推导式写法 | |
squared = [num ** 2 for num in numbers] |
-
字典推导式 (Dictionary Comprehension)
python复制代码
# 常规写法 | |
keys = ['a', 'b', 'c'] | |
values = [1, 2, 3] | |
dictionary = {} | |
for key, value in zip(keys, values): | |
dictionary[key] = value | |
# 字典推导式写法 | |
dictionary = {key: value for key, value in zip(keys, values)} |
-
集合推导式 (Set Comprehension)
python复制代码
# 常规写法 | |
numbers = [1, 2, 2, 3, 4, 4, 5] | |
unique_numbers = set() | |
for num in numbers: | |
unique_numbers.add(num) | |
# 集合推导式写法 | |
unique_numbers = {num for num in numbers} |
-
if-else 表达式
python复制代码
# 常规写法 | |
x = 10 | |
if x > 0: | |
y = "positive" | |
else: | |
y = "non-positive" | |
# if-else 表达式写法 | |
y = "positive" if x > 0 else "non-positive" |
- 三元操作符 (Ternary Operator)
与上面的 if-else 表达式相同,但更明确地称为三元操作符。
6. 多行字符串 (Multi-line Strings)
python复制代码
# 使用三引号 | |
multiline_string = """ | |
This is a multi-line string. | |
It can span multiple lines. | |
""" |
-
交换两个变量的值
python复制代码
# 常规写法 | |
a, b = 1, 2 | |
temp = a | |
a = b | |
b = temp | |
# 简洁写法 | |
a, b = b, a |
-
函数参数默认值
python复制代码
def greet(name, greeting="Hello"): | |
print(greeting, name) | |
greet("Alice") # 输出: Hello Alice | |
greet("Bob", "Hi") # 输出: Hi Bob |
-
使用
enumerate
遍历列表的同时获取索引
python复制代码
for index, value in enumerate(['a', 'b', 'c']): | |
print(index, value) |
-
使用
zip
同时遍历多个列表
python复制代码
list1 = [1, 2, 3] | |
list2 = ['a', 'b', 'c'] | |
for item1, item2 in zip(list1, list2): | |
print(item1, item2) |
-
使用
with
语句自动管理资源(如文件)
python复制代码
with open('file.txt', 'r') as file: | |
data = file.read() | |
# 文件在这里会自动关闭 |
-
使用
in
关键字检查元素是否存在于列表中
python复制代码
numbers = [1, 2, 3, 4, 5] | |
if 3 in numbers: | |
print("3 is in the list.") |
-
使用
not in
关键字检查元素是否不存在于列表中
python复制代码
numbers = [1, 2, 3, 4, 5] | |
if 6 not in numbers: | |
print("6 is not in the list.") |
-
使用
**
展开字典
python复制代码
def func(**kwargs): | |
for key, value in kwargs.items(): | |
print(key, value) | |
func(a=1, b=2, c=3) # 输出: a 1, b 2, c 3 |
-
使用
*
展开列表或元组
python复制代码
def func(*args): | |
for arg in args: | |
print(arg) | |
func(1, 2, 3) # 输出: 1, 2, 3 |
- 使用
lambda
关键字定义匿名函数