常用的python优雅写法

Python 以其简洁、易读和优雅的语法而著称。以下是一些常用的优雅简洁的 Python 语法写法,掌握后可以很大的提升开发效率:

  1. 列表推导式 (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]
  1. 字典推导式 (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)}
  1. 集合推导式 (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}
  1. if-else 表达式

 

python复制代码

# 常规写法
x = 10
if x > 0:
y = "positive"
else:
y = "non-positive"
# if-else 表达式写法
y = "positive" if x > 0 else "non-positive"
  1. 三元操作符 (Ternary Operator)

与上面的 if-else 表达式相同,但更明确地称为三元操作符。
6. 多行字符串 (Multi-line Strings)

 

python复制代码

# 使用三引号
multiline_string = """
This is a multi-line string.
It can span multiple lines.
"""
  1. 交换两个变量的值

 

python复制代码

# 常规写法
a, b = 1, 2
temp = a
a = b
b = temp
# 简洁写法
a, b = b, a
  1. 函数参数默认值

 

python复制代码

def greet(name, greeting="Hello"):
print(greeting, name)
greet("Alice") # 输出: Hello Alice
greet("Bob", "Hi") # 输出: Hi Bob
  1. 使用 enumerate 遍历列表的同时获取索引

 

python复制代码

for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
  1. 使用 zip 同时遍历多个列表

 

python复制代码

list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
for item1, item2 in zip(list1, list2):
print(item1, item2)
  1. 使用 with 语句自动管理资源(如文件)

 

python复制代码

with open('file.txt', 'r') as file:
data = file.read()
# 文件在这里会自动关闭
  1. 使用 in 关键字检查元素是否存在于列表中

 

python复制代码

numbers = [1, 2, 3, 4, 5]
if 3 in numbers:
print("3 is in the list.")
  1. 使用 not in 关键字检查元素是否不存在于列表中

 

python复制代码

numbers = [1, 2, 3, 4, 5]
if 6 not in numbers:
print("6 is not in the list.")
  1. 使用 ** 展开字典

 

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
  1. 使用 * 展开列表或元组

 

python复制代码

def func(*args):
for arg in args:
print(arg)
func(1, 2, 3) # 输出: 1, 2, 3
  1. 使用 lambda 关键字定义匿名函数
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值