py的十个小技巧
通过B站学习
(一)变量交换
a=1
b=2
tmp=a
a=b
b=tmp
print(a)
print(b)
#改为
a,b=b,a
(二)字符串格式化
name = 'xiaowang'
country = 'China'
age = 19 # 需要转类型
print("Hi,I'm" + name + ". I'm from" + country + ". And I'm " + str(age) + ".")
# 改为
print("Hi,I'm %s. I'm from %s. And I'm %i." % (name, country, age)) # 注意%()
# 当然可以使用format函数
print("Hi,I'm {}. I'm from {}. And I'm {}.".format(name, country, age)) # 可以通过索引改同一个
# py3.6以上可以使用f-string
print(f"Hi,I'm {name}. I'm from {country}. And I'm {age+1}.") # 最简洁
(三)Yield 语法
def fibonacci(n): # 斐波那契数列函数
a = 0
b = 1
nums = []
for _ in range(n):
nums.append(a)
a, b = b, a + b
return nums
def fibonacci1(m):
a = 0
b = 1
for _ in range(m):
yield a
a, b = b, a + b
for i in fibonacci(10):
print(i)
print('-------------------------------')
for i in fibonacci1(10):
print(i)
(四)列表解析式
fruit=["apple","pear","pineapple","orange","banana"] # 改大写
for i in range(len(fruit)):
fruit[i]=fruit[i].upper()
# 改为
fruit=[x.upper()for x in fruit]
print(fruit)
# 挑选
a_fruit=list()
for f in fruit:
if f.startswith("A"):
a_fruit.append(f)
#改为
a_fruit=[x for x in fruit if x.startswith("A")]
(五)enumerate函数
fruit = ["apple", "pear", "pineapple", "orange", "banana"]
for x in fruit:
print(x) # 如果想去获取索引值
for i,x in enumerate(fruit):
print(i,x)
(六)遍历
A.反向遍历
fruit = ["apple", "pear", "pineapple", "orange", "banana"]
for i,x in enumerate(reversed(fruit)):
print(i,x)
B.顺序遍历
fruit = ["apple", "pear", "pineapple", "orange", "banana"]
for i,x in enumerate(sorted(fruit)):# sorted排序函数
print(i,x)
(七)字典合并操作
a = {"xiaowang": "123456", "xiaoming": "abc123"}
b = {"keai": "666666", "xiaozhao": "321321"}
c={}
for k in a:
c[k]=a[k]
for k in b:
c[k]=b[k]
# 改为
c={**a,**b}
(八)三元运算
s="pass" if score >60 else "fail"
(九)序列的解包
name = "Zhan San"
str_list = name.split()
first_name = str_list[0]
last_name = str_list[1]
# 改为
first_name, last_name = name.split()
(十)with语句
f=open("xx.txt","r")
s=f.read()
f.close()
#改为
with open("xx.txt","r") as f # 代替f.close
s=f.read()