交换变量
10x=6
y=5
x,y=y,x
printx
>>>5
printy
>>>6
if 语句在行内
1
2
3print"Hello"ifTrueelse"World"
>>>Hello
连接
下面的最后一种方式在绑定两个不同类型的对象时显得很酷。
16nfc=["Packers","49ers"]
afc=["Ravens","Patriots"]
printnfc+afc
>>>['Packers','49ers','Ravens','Patriots']
printstr(1)+" world"
>>>1world
print`1`+" world"
>>>1world
print1,"world"
>>>1world
printnfc,1
>>>['Packers','49ers']1
计算技巧
7#向下取整
print5.0//2
>>>2
# 2的5次方
print2**5
>>32
注意浮点数的除法
1
2
3
4
5print.3/.1
>>>2.9999999999999996
print.3//.1
>>>2.0
数值比较
8x=2
if3>x>1:
printx
>>>2
if10:
printx
>>>2
两个列表同时迭代
7nfc=["Packers","49ers"]
afc=["Ravens","Patriots"]
forteama,teambinzip(nfc,afc):
printteama+" vs. "+teamb
>>>Packersvs.Ravens
>>>49ersvs.Patriots
带索引的列表迭代
8teams=["Packers","49ers","Ravens","Patriots"]
forindex,teaminenumerate(teams):
printindex,team
>>>0Packers
>>>149ers
>>>2Ravens
>>>3Patriots
列表推导
已知一个列表,刷选出偶数列表方法:
6numbers=[1,2,3,4,5,6]
even=[]
fornumberinnumbers:
ifnumber%2==0:
even.append(number)
用下面的代替
1
2
3numbers=[1,2,3,4,5,6]
even=[numberfornumberinnumbersifnumber%2==0]
字典推导
1
2
3
4teams=["Packers","49ers","Ravens","Patriots"]
print{key:valueforvalue,keyinenumerate(teams)}
>>>{'49ers':1,'Ravens':2,'Patriots':3,'Packers':0}
初始化列表的值
1
2
3
4items=[0]*3
printitems
>>>[0,0,0]
将列表转换成字符串
1
2
3
4teams=["Packers","49ers","Ravens","Patriots"]
print", ".join(teams)
>>>'Packers, 49ers, Ravens, Patriots'
从字典中获取元素
不要用下列的方式
6data={'user':1,'name':'Max','three':4}
try:
is_admin=data['admin']
exceptKeyError:
is_admin=False
替换为
1
2
3data={'user':1,'name':'Max','three':4}
is_admin=data.get('admin',False)
获取子列表
17x=[1,2,3,4,5,6]
#前3个
printx[:3]
>>>[1,2,3]
#中间4个
printx[1:5]
>>>[2,3,4,5]
#最后3个
printx[-3:]
>>>[4,5,6]
#奇数项
printx[::2]
>>>[1,3,5]
#偶数项
printx[1::2]
>>>[2,4,6]
60个字符解决FizzBuzz
前段时间Jeff Atwood 推广了一个简单的编程练习叫FizzBuzz,问题引用如下:
1
2写一个程序,打印数字1到100,3的倍数打印“Fizz”来替换这个数,5的倍数打印“Buzz”,对于既是3的倍数又是5的倍数的数字打印“FizzBuzz”。
这里有一个简短的方法解决这个问题:
1
2forxinrange(101):print"fizz"[x%3*4::]+"buzz"[x%5*4::]orx
集合
用到Counter库
1
2
3
4fromcollectionsimportCounter
printCounter("hello")
>>>Counter({'l':2,'h':1,'e':1,'o':1})
迭代工具
和collections库一样,还有一个库叫itertools
11fromitertoolsimportcombinations
teams=["Packers","49ers","Ravens","Patriots"]
forgameincombinations(teams,2):
printgame
>>>('Packers','49ers')
>>>('Packers','Ravens')
>>>('Packers','Patriots')
>>>('49ers','Ravens')
>>>('49ers','Patriots')
>>>('Ravens','Patriots')
False == True
在python中,True和False是全局变量,因此:
7False=True
ifFalse:
print"Hello"
else:
print"World"
>>>Hello
怎么样才能学好python学好python你需要一个良好的环境,一个优质的开发交流群,群里都是那种相互帮助的人才是可以的,我有建立一个python学习交流群,在群里我们相互帮助,相互关心,相互分享内容,这样出问题帮助你的人就比较多,群号是301,还有056,最后是069,这样就可以找到大神聚合的群,如果你只愿意别人帮助你,不愿意分享或者帮助别人,那就请不要加了,你把你会的告诉别人这是一种分享。如果你看了觉得还可以的麻烦给我点个赞谢谢
。