Python初学者的17个技巧
来源:互联网 发布:哪些明星开了淘宝店 编辑:程序博客网 时间:2024/04/29 08:46
以下是我在Python学习过程中,总结的一些小技巧。不对之处还希望大家指正。
交换变量
x = 6y = 5x, y = y, xprint x>>>5print y>>>6
if语句在行内
print "hello" if True else "World">>>Hello
连接
下面的最后一种方式在绑定两个不同类型的对象时显得很酷。
nfc = ["Packers","49ers"] afc = ["Ravens ", " Patriots"] print nfc + afc>>> ['Packers', '49ers', 'Ravens', 'Patriots']print str(1) + "world">>> 1 worldprint '1' + "world">>>1 worldprint 1, "world">>>1 worldprint nfc ,1>>> ['Packers', '49ers'] 1
计算技巧
#向下取整print 5.0//2>>>2#2的5次方print 2**5>> 32
注意浮点数的除法
print .3/.1>>>2.9999999999999996print .3//.1>>>2.0
数值比较
x = 2if 3 > x > 1: print x>>> 2if 1 < x > 0 print x>>> 2
两个列表同时迭代
nfc = ["Packers", "49ers"]afc = ["Ravens", "Patriots"]for teama, teamb in zip(nfc, afc): print teama + " vs ." + teamb>>> Packers vs. Ravens>>> 49ers vs. Patriots
带索引的列表迭代
teams = ["Packers", "49ers", "Ravens", "Patriots"]for index, team in enumerate(teams): print index, team>>> 0 Packers>>> 1 49ers>>> 2 Ravens>>> 3 Patriots
列表推导
已知一个列表,刷选出偶数列表方法:
numbers = [1,2,3,4,5,6]even = []for number in numbers: if number %2 == 0: even.append(number)
用下面的代替
numbers = [1,2,3,4,5,6]even = [number for number in numbers ]
初始化列表的值
items = [0] * 3print items>>> [0,0,0]
将列表转换成字符串
teams = ["Packers", "49ers", "Ravens", "Patriots"]print", ".join(teams)>>>'Packers,49ers,Ravens,Patriots'
获取子列表
x = [1,2,3,4,5,6]#前3个print x[:3]>>> [1,2,3]#中间4个print x[1:5]>>> [2,3,4,5]#最后3个print x [-3:]>>> [4,5,6]#奇数项print x[::2]>>> [1,3,5]#偶数项print x[1::2]>>> [2,4,6]
迭代工具
和collections库一样,还有一个库叫itertools。
from itertools import combinationsteams = ["Packers", "49ers", "Ravens", "Patriots"]for game in combinations (teams, 2): print game>>> ('Packers','49ers')>>> ('Packers', 'Ravens' )>>> ('Packers', 'Patriots' )>>> ('49ers', 'Ravens' ) >>> ('49ers', 'Patriots' ) >>> ('Ravens', 'Patriots' )
在python中,True和False是全局变量,因此:
False = Trueif False: print "Hello"else: print "World">>>Hello
0 0
- Python初学者的17个技巧
- Python初学者的17个技巧
- Python初学者的17个技巧
- Python初学者的17个技巧
- Python初学者的17个技巧
- Python初学者的17个技巧
- Python初学者的18个技巧
- Python初学者的18个技巧
- Python初学者的技巧总结
- python的17个技巧
- ASP初学者的10个编程技巧
- JavaScript初学者的10个迷你技巧
- 献给初学者的10个Git技巧
- 给Python初学者的一些技巧
- 给Python初学者的一些技巧
- 给Python初学者的一些技巧
- 给Python初学者的一些技巧
- 给Python初学者的一些技巧
- 10.1补
- 函数调用
- css first-letter实现首字(字母)下沉效果
- SSH免密码登录
- POJ2891 Strange Way to Express Integers 不互质中国剩余定理
- Python初学者的17个技巧
- Android listview与adapter用法
- 关于多物体运动框架的函数
- codeforces round353 tree construction
- 关于Illegal partition for
- 算法笔试题(一):求数字N以内最大质数
- ECMAScript 6 学习笔记----异步操作和Async函数
- 排序算法
- 创新思维训练--蛋的思考