pythonic
指的是具有python独特风格,简洁而又优雅的代码
- 变量交换(Swapping Variables)
# 通常的做法
a = 1
b = 2
tmp = a
a = b
b = tmp
# tmp是临时变量
# 在Python中我们可以这样做
a = 1
b = 2
a,b = b,a
- 字符串格式化(String Formatting)
# 当字符串较多时,通常拼接字符串会很麻烦,如:
name = "Ross"
country = "China"
age = "18"
print("Hi,I'm" + name +"I'm form" + country + ",And I'm" + str(age) + ".")
# 在Python中我们可以这样做
# 1利用Python中的%语法来格式化字符串
print("Hi,I'm %s. I'm from %s. And I'm %d."%(name,country,age))
# 这里%s(string)会被替换成一个字符串 %d(decimal)会被替换成一个十进制数
# 2利用.format()方法和{}语法
print("Hi,I'm {}. I'm from {}. And I'm {}.".format(name,country,age))
# 另一个好处是可以使用参数的索引来重复替换 如:
print("Hi,I'm {0}.Yes,I'm {0}.".format(name))
# 3最简单的写法Python3.6后支持的语法 f—string
print(f"Hi,I'm {name}. I'm from {country}. And I'm {age}.")
# 最大的好处是{}里的内容支持表达式
- Yield语法(Yield Statemaent)
# 斐波那契数列
def fibonacci(n):
a = 0
b = 1
nums = []
for _ in range(n):
nums.append(a)
a,b = b,a+b
return nums
for i in fibonacci(10):
print(i)
# 在Python中我们可以借助yield语法替换append方法
def fibonacci(n):
a = 0
b = 1
for _ in range(n):
yield a
a,b = b,a+b
for i in fibonacci(10):
print(i)、
# yield表示每当我们计算出一个元素 就立马实时将这个元素送出去
- 列表解析式(List Comprehension)
# 这里有一些水果名字,将它们都改成大写
fruit = ["apple","pear","pineapple","arange","banana"]
# 在Python中我们可以这样
fruit = [x.upper() for x in fruit]
# 也可以筛选列表中的元素
filtered_fruit = [x for x in fruit if x.startswitch("a")]
- Enumerate 函数(Enumerate Function)循环技巧
# 还是上面的例子
fruit = ["apple,"pear","pineapple","arange","banana"]
for i,x in emumerate(fruit):
print(i,x)
# 其中i代表索引值,x表示元素
6.1 反向遍历(Looping Backwards)
# 我们可以先这样实现
fruit = ["apple,"pear","pineapple","arange","banana"]
for i,x in emumerate(reverse(fruit)):
print(i,x)
6.2 按顺序遍历(Looping in Sorted Order)
# 如果我们希望输出的元素是以字典顺序
# 我们可以先这样实现
fruit = ["apple,"pear","pineapple","arange","banana"]
for i,x in emumerate(sorted(fruit)):
print(i,x)
- 字典合并操作(Dictionary Merging)
# 下面是一般的字典合并
a = {"ross":"123456","xiaoming":"abc123"}
b = {"lilei":"111111","zhangsan":"12345678"}
c = {}
for k in a:
c[k] = a[k]
for k in b:
c[k] = b[k]
# 在python中我们可以
a = {"ross":"123456","xiaoming":"abc123"}
b = {"lilei":"111111","zhangsan":"12345678"}
c = {**a,**b}
# **叫做解包(Unpacking),将两个字典直接填写到这里
- 三元运算符(Ternary Operator)
# 可以对if else语句简化
if score > 60:
s = "pass"
else:
s = "fail"
# 在python中我们可以
s = "pass" if score > 60 else "fail"
- 序列解包(Sequence Unpacking)
# 提取姓和名
name = "San Zhang"
str_list = name.spilt()
first_name = str_list[0]
last_name = str_list[1]
# 在python中我们可以这样
name = "San Zhang"
first_name , last_name = name.split()
- With语句(With Statement)
# with open("somefile.txt","r") as f"
s = read()