Python部落(www.freelycode.com)组织翻译, 禁止转载
错误的默认值会导致下面的结果>>> def foo(x=[]):... x.append(1)... print x... >>> foo()[1]>>> foo() [1, 1] # A should be [1]>>> foo()[1, 1, 1]
这时应该把默认值设置为None>>> def foo(x=None):... if x is None:... x = []... x.append(1)... print x>>> foo()[1]>>> foo()[1]
字典的__missing__内置方法
__missing__内置方法消除了KeyError异常, 重新定义了找不到Key时的返回.class MyDict(dict): # The function of creating a dictionary def __missing__(self, key): return key...>>> m = MyDict(a=1, b=2, c=3) >>> m{'a': 1, 'c': 3, 'b': 2}>>> m['a'] # The key exists and returns 11>>> m['z'] # Key does not exist and returns the name of the requested key'z'
以函数为变量
>>> def jim(phrase):... return 'Jim says, "%s".' % phrase>>> def say_something(person, phrase):... print person(phrase)>>> say_something(jim, 'hey guys')
更高阶的体现def f(x): return x + 3def g(function, x): return function(x) * function(x)print g(f, 7)
负的round>>> round(1234.5678, -2)1200.0>>> round(1234.5678, 2)1234.57
如果你想像C语言一样用{}代替缩进from __future__ import braces跳步切片a = [1,2,3,4,5]>>> a[::2] # indicate step[1,3,5]或者反着跳>>> a[::-1] # Reverse list[5,4,3,2,1]在浏览器中打开页面import webbrowserwebbrowser.open_new_tab('http://facebook.com/') #Returns True and open tabzip合并列表a = [(1,2), (3,4), (5,6)]zip(*a)# [(1, 3, 5), (2, 4, 6)]在字典中合并两个列表>>> t1 = (1, 2, 3)>>> t2 = (4, 5, 6)>>> dict (zip(t1,t2)){1: 4, 2: 5, 3: 6}操作列表切片>>> a = range(10)>>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> a[:5] = [42] # All symbols up to 5 be replaced by "42">>> a[42, 5, 6, 7, 8, 9]>>> a[:1] = range(5) >>> a[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> del a[::2] # Delete every second element>>> a[1, 3, 5, 7, 9]>>> a[::2] = a[::-2] # Alternative reserved>>> a[9, 3, 5, 7, 1]最后热爱未知, 阅读文档!英文原文: https://www.devbattles.com/en/sand/post-1799-Python_the_things_that_you_might_not_know译者: 诗书塞外