Python的一些隐藏特性


在Stackoverflow上看到的一则小技巧:Hidden features of Python,与之类似的还有 C/C#/Java/Javascript/Perl/Shell 等语言,值得去学习学习,以写出更优美的代码(不知道这个会被会被笑话太屌丝了……)

What are the lesser-known but useful features of the Python programming language?

  • Try to limit answers to Python core.
  • One feature per answer.
  • Give an example and short description of the feature, not just a link to documentation.
  • Label the feature using a title as the first line.

Quick links to answers:

还有一些我觉得不错的有:

  • 字符串查找
  • 复杂的列表推导式
  • 内建的各种编解码方法
  • 矩阵转置
  • 利用pow()函数进行快速计算
  • 多行字符串的3种实现方式
  • round()函数的一些小技巧
  • ……

 

补充一下Stackoverflow上的『Hidden Features系列』:

All in all: http://stackoverflow.com/search?q=Hidden+Features+of+

 


拓展链接:

http://search.aol.com/aol/search?q=python+hidden+features

相关拓展:

http://beerpla.net/2009/06/21/hidden-features-of-perl-php-javascript-c-c-c-java-ruby-python-and-others-collection-of-incredibly-useful-lists/

For .. else syntax
for i in (1, 2, 4):
    if i == 0:
        break
else: print("i was never 0")

 

https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences

 

  • 字典的get方法
  • for/else语句
  • generator
  • iterator
  • 就地置换(>>> a, b = b, a)
  • 列表切片
  • with语句块
  • 列表/字典推导式
  • 嵌套列表/字典
  • 格式化命名{Named formatting}
  • 条件赋值{Conditional Assignment}(三元操作符:>>> ‘ham’
  • if True else ‘spam’)
  • enumerate方法
  • 比较运算符的拼接{比如:1 < x < 10}
  • set操作的运算符重载
  • 多行字符串{三重引号}
  • 幂函数pow()(pow() can also calculate (x ** y) % z efficiently)
  • zip()函数(用于list合并)
  • dir()和help()函数(当然最好的肯定是IPython)
  • 内置的一些功能性函数(encode()/split()/join()/count()) https://docs.python.org/2/library/functions.html
  • 序列乘积(>>> ‘xyz’ * 3)
  • sort()和sorted()函数
  • 特殊语法:filter、map、reduce、lambda https://docs.python.org/2/library/functions.html

字典(使用大括号,并用冒号分隔key/value)
https://docs.python.org/2/library/stdtypes.html#mapping-types-dict

元组(tuple) tuple=(1,),这是单个元素的元组表示,需加额外的逗号。tuple=1,2,3,4,这也可以是一个元组,在不使用圆括号而不会导致混淆时,Python允许不使用圆括号的元组。
https://docs.python.org/2/library/functions.html#tuple

,

《“Python的一些隐藏特性”》 有 4 条评论

  1. 像这种帖子你是怎么翻到的啊?我也常用Stackoverflow,但就没发现之类帖子……

    • 有时候是从别人那看到的,有些是无意中翻到的,刻意去找反而不那么方便。

  2. 一些有趣且鲜为人知的 Python 特性
    https://github.com/leisurelicht/wtfpython-cn
    `
    Python, 是一个设计优美的解释型高级语言, 它提供了很多能让程序员感到舒适的功能特性. 但有的时候, Python 的一些输出结果对于初学者来说似乎并不是那么一目了然.

    这个有趣的项目意在收集 Python 中那些难以理解和反人类直觉的例子以及鲜为人知的功能特性, 并尝试讨论这些现象背后真正的原理!

    虽然下面的有些例子并不一定会让你觉得 WTFs, 但它们依然有可能会告诉你一些你所不知道的 Python 有趣特性. 我觉得这是一种学习编程语言内部原理的好办法, 而且我相信你也会从中获得乐趣!
    `

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注