《The Python Tutorial》中知识点补充

来源:互联网 发布:软件卡住关不掉 编辑:程序博客网 时间:2024/06/16 17:11
python3官方文档中文版:http://wiki.jikexueyuan.com/project/python-tutorial/stdlib-two.html



1.join():一个一个使用

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'

2.lambda当中的x这样赋值:
>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42

3._doc_:调用函数的注释
>>> def my_function():
...     """Do nothing, but document it.
...
...     No, really, it doesn't do anything.
...     """
...     pass
...
>>> print(my_function.__doc__)

4.__annotations__:Annotations are stored in the __annotations__ attribute of the function as a dictionary and have no effect on any other part of the function.
>>> def f(ham: str, eggs: str = 'eggs') -> str:
...     print("Annotations:", f.__annotations__)
...     print("Arguments:", ham, eggs)
...     return ham + ' and ' + eggs
...
>>> f('spam')
Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

5. list.extend(iterable):添加一个可迭代值(和append的区别):
     In [1]: lt1=['A','B','C']  
       ...: lt2=['D','E','F']  
       ...: lt1.append(lt2)#将lt2整体当作一个元素追加到到lt1中  
       ...: print(lt1)  
       ...: lt3=['A','B','C']  
       ...: lt2=['D','E','F']  
       ...: lt3.extend(lt2)#将lt2中每个元素逐个追加到t3中  
       ...: print(lt3)  
       ...:  
    ['A', 'B', 'C', ['D', 'E', 'F']]  
    ['A', 'B', 'C', 'D', 'E', 'F']  
    
6.list.clear():清除全部
常见的列表操作:
 >>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4)  # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

7.列表表达式(简化程序):>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

8.字典表达式(简化程序):>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

9.not math.isnan(value):判断是一个数值

10.python中:not比and和or优先级更高

11.python中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值;or也是从左到有计算表达式,返回第一个为真的值。


 12.__name__ == "__main__":表示在函数不作为模块时调用时(即不用import时),可以当作交互代码直接运行他(__name__ == "__main__"其中已经赋予函数参数),例$ python fibo.py 50,直接在命令行运行
if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))
    
13.dir():查看模块拥有的函数(记住先要import模块)

14.字符串对象的str.rjust()方法,它通过在左侧填充空格使字符串在给定的宽度的列右对齐|| print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) :{2:2d} 第一个是第几个参数,第二个的2d 是这个参数的类型,下面的例子是将Pi 转为三位精度

15.str.zfill(),它向数值字符串左侧填充零。该函数可以正确识别正负号,如果字符串长度的值小于zfill() 参数的值,那么就会在数值字符串前面补零,如果字符串长度的值大于或等于zfill() 参数的值,那么它就保持原样。(http://blog.csdn.net/jeff_liu_sky_/article/details/52454113)

16.format():
可以用括号中的数字指定传递给str.format()方法的对象的位置。
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

17.如果str.format()方法使用关键字参数,那么将通过参数名引用它们的值。

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
    1
    2
    3
位置参数和关键字参数可以随意组合:
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.

18.如果有一个实在很长的格式字符串但又不想分开,要是可以按照名字而不是位置引用变量就好了。有个简单的方法,可以传入一个字典,然后使用’[]’访问。
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

19.raise():例raise NameError('HiThere'):写一段关于错误的注释。
20.finally从句总是被执行。
21.iter(s):将对象变为可迭代的对象

22.常用模块:
re:正则表达式
statistics:统计模块
http:会处理所有客户端--服务器http请求的具体细节
urllib是基于http的高层库,它有以下三个主要功能:
(1)request处理客户端的请求
(2)response处理服务端的响应
(3)parse会解析url
原创粉丝点击