Python--如此高效的代码片段
2016-10-26 23:46
387 查看
出自:
http://www.maxburstein.com/blog/python-shortcuts-for-the-python-beginner/
我是一个C++程序员,所以把拿C++与Python进行比较,从而来显示Python的高效。
交换变量
交换两个变量的值,应该是应届毕业生面试常见的问题,在c++中,我们使用指针或是引用来完成,或是使用位运算完成,不借助第三方变量等等。那么看看python呢?
内联if语句
连接
在C++中,字符串连接都是重载了+或是+=运算符,数组不能进行连接。在python中很简单:
数字技巧
幂运算:
在C++中,可以使用pow,但是在python中非常的简便:
2的5次幂:
比较
在C++中,比如x大于1小于3,我们要这样:x > 1 && x < 3,在python中更接近数学形式:
并行迭代
这是C++中没有的。
使用索引迭代(遍历)
从列表中去除偶数
可以像C++一样,python可以:
python有更简便的方法:
初始化列表
c++11中的初始化列表,已经让我们觉得很牛逼了,但是看看python中:
列表转字符串
http://www.maxburstein.com/blog/python-shortcuts-for-the-python-beginner/
我是一个C++程序员,所以把拿C++与Python进行比较,从而来显示Python的高效。
交换变量
交换两个变量的值,应该是应届毕业生面试常见的问题,在c++中,我们使用指针或是引用来完成,或是使用位运算完成,不借助第三方变量等等。那么看看python呢?
x = 6 y = 5 x, y = y, x
内联if语句
print "Hello" if True else "World" >>> Hello
连接
在C++中,字符串连接都是重载了+或是+=运算符,数组不能进行连接。在python中很简单:
nfc = ["Packers", "49ers"] afc = ["Ravens", "Patriots"] print nfc + afc >>> ['Packers', '49ers', 'Ravens', 'Patriots'] print str(1) + " world" >>> 1 world print `1` + " world" >>> 1 world print 1, "world" >>> 1 world print nfc, 1 >>> ['Packers', '49ers'] 1
数字技巧
幂运算:
在C++中,可以使用pow,但是在python中非常的简便:
2的5次幂:
print 2**5 >> 32
比较
在C++中,比如x大于1小于3,我们要这样:x > 1 && x < 3,在python中更接近数学形式:
x = 2 if 3 > x > 1: print x >>> 2 if 1 < x > 0: print x >>> 2
并行迭代
这是C++中没有的。
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
从列表中去除偶数
可以像C++一样,python可以:
numbers = [1,2,3,4,5,6] even = [] for number in numbers: if number%2 == 0: even.append(number)
python有更简便的方法:
numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0]
初始化列表
c++11中的初始化列表,已经让我们觉得很牛逼了,但是看看python中:
items = [0]*3 print items >>> [0,0,0]
列表转字符串
teams = ["Packers", "49ers", "Ravens", "Patriots"] print ", ".join(teams) >>> 'Packers, 49ers, Ravens, Patriots'
相关文章推荐
- Python--如此高效的代码片段
- 高效Web开发的10个jQuery代码片段
- 分享一下如何编写高效且优雅的 Python 代码
- 高效Web开发的10个jQuery代码片段
- Python开发工具 Wing IDE Snippet 代码片段 快捷键 设置
- python实用代码片段收集贴
- python 代码片段8
- 常用aws2 python 和 boto代码片段
- 高效Web开发的10个jQuery代码片段
- [python实用代码片段]python获取当前时间的前一天,前一周,前一个月
- python 功能代码安全高效写法
- 完爆程序员!谷歌AI写的机器学习代码竟如此高效
- python 代码片段4
- python 代码片段17
- 高效Web开发的10个jQuery代码片段(转)
- 常用python日期、日志、获取内容循环的代码片段
- [转]Python 常用代码片段
- Python 常用代码片段
- Python 3.2 常用代码片段之-十进制转化为二进制
- python代码高效经验