今天给大家分享几个python的小技巧,希望你们在编码的时候可以用得上。
1、交换变量
如果在其它语言中两个变量交换值,就需要一个中间变量,如下所示:
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#交换变量
a=1
b=2
temp=0
print(a,b)
temp=a
a=b
b=temp
print(a,b)
但是实际在python中并不需要这样麻烦,只需要这样就可以了
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#交换变量
a=1
b=2
print(a,b)
a,b=b,a
print(a,b)
2、取出列表子集
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#取出列表的子集
words = ['菜鸟', '小白的', '学习', '分享']
sub = words[:2]
print(sub)
程序运行结果:
这种方式同样适用于字符串
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#取出字符串的子串
words = '菜鸟小白的学习分享'
sub = words[:4]
print(sub)
运行结果如下:
3、条件判断
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
flag = True
if flag:
x = 1
else:
x = 2
print(x)
可以修改为
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
flag = True
x = 1 if flag else 2
print(x)
4、文件打开关闭
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#文件打开关闭
f = open('菜鸟小白.txt','r',encoding='utf-8')
contents = f.read()
f.close()
words = contents.split(' ')
word_counts = len(words)
print(word_counts)
修改后
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#文件打开关闭
with open('菜鸟小白.txt','r',encoding='utf-8') as f:
contents = f.read()
words = contents.split(' ')
word_counts = len(words)
print(word_counts)
5、下标的使用
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#下标的使用
words=['菜鸟','小白','学习','分享']
index=0
for name in words:
print (index,words)
index+=1
修改后
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#下标的使用
words=['菜鸟','小白','学习','分享']
for index,name in enumerate(words):
print (index,words)
6、遍历多个序列
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#遍历多个序列
words=['菜鸟','小白的','学习','分享']
nums=[2,3,2,2]
for index,word in enumerate(words):
num=nums[index]
print (f'{word} 有 {num} 个字')
修改后
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#遍历多个序列
words=['菜鸟','小白的','学习','分享']
nums=[2,3,2,2]
for word,num in zip(words,nums):
print (f'{word} 有 {num} 个字')
7、dir函数
你是否存在拿到一个python对象,却不知道它有哪些属性的情况。这个时候你就可以使用dir函数。使用方法如下:
# -*- coding:utf-8 -*-
#author:菜鸟小白的学习分享
#dir
words=['菜鸟','小白的','学习','分享']
print(dir(words))
执行结果如下:
"C:\Program Files\Python36\python.exe" C:/Users/admin/PycharmProjects/20200701/test.py
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Process finished with exit code 0