1. 条件判断
condition=True
if condition:
x=1
else:
x=2
print (x)
改成
x=1 if condition else 2
print (x)
2.文件的关闭
f=open('log.txt','r')
file_contents=f.read()
f.close()
words=file_contents.split(' ')
word_count=len(words)
print (word_count)
用with来处理更简便
with open('log.txt','r') as f:
file_contents=f.read()
words=file_contents.split(' ')
word_count=len(words)
print (word_count)
3.优雅的用下标
names=['Corey','Chris','Dave','Apple']
index=0
for name in names:
print (index,name)
index+=1
使用enumerate来计算下标
names=['Corey','Chris','Dave','Apple']
for index,name in enumerate(names):
print (index,name)
4.遍历多个序列
names=['Leo','Lili','Sam','Tom']
ages=[30,20,28,25]
for index,name in enumerate(names):
age=ages[index]
print (f'{name} is {age} old')
太麻烦了,用zip更方便
for name ,age in zip(names,ages):
print (f'{name} is {age} old')
有的同学说如果我有3个序列呢,怎么办,一样可以操作
names=['Leo','Lili','Sam','Tom']
ages=[30,20,28,25]
habits=['Movies','Dance','Reading','Singing']
for name ,age,habit in zip(names,ages,habits):
print (f'{name} is {age} old and like {habit}')
5.巧妙的使用单下划线
a,_,b=(1,2,3)
print (a)
print (b)
>>
1
3
如果有一个很长的序列的时候,我们想取头和尾怎么办呢,传统的做法是:
nums=(1,2,3,4,5,6,7,8,9)
head=nums[0]
tail=nums[-1]
print (head)
print (tail)
如果能巧妙的利用unpack方法,就会很简便:
nums=(1,2,3,4,5,6,7,8,9)
head,*_,tail=nums
print (head)
print (tail)
6.类的属性封装
class Person():
pass
person=Person()
如果你有一个字典需要来初始化这个类
person_info={'first':'leo','last':'sam'}
你希望最后能print (person.first),怎么办?有没有什么巧妙的方法处理?
用setattr函数
for k,v in person_info.items():
setattr(person,k,v)
还有getattr(),可以方便的获取类的属性
for k in person_info.keys():
print (getattr(person,k))
7.输入加密的密码
username=input('Username: ')
passwd=input('Passwd:')
print ('Logging In...')
>>
Username: user
Passwd:admin
Logging In...
密码是显示出来的,这样肯定不太好,有没有其他优雅的方法的,用Python自带的函数getpass
from getpass import getpass
username=input('Username: ')
passwd=getpass('Passwd:')
print ('Logging In...')
>>
Username: aa
Passwd: