Python document-The python tutorial



28视频:
  正则表达式常用函数:
  


35视频:
>>> import os
>>> g=os.walk("d:/test")
>>> os.walk("d:/test")
<generator object walk at 0x06B848F0>      //产生一个walk对象的生成器。
>>> for i in g:
...     print g
...     
<generator object walk at 0x06B83AD0>
<generator object walk at 0x06B83AD0>
<generator object walk at 0x06B83AD0>
>>> 




-----------------------------------------------




---------------------
>>> a=[[3,4,5],[3,2,1]]   //一个列表
>>> import numpy
>>> numpy.array(a)        //将列表转换为数组。
array([[3, 4, 5],
       [3, 2, 1]])
>>> numpy.array(a).shape[0]   //求数组有几行。
2
>>> 
--------------------------------------
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> len(a)//2                 //取整
5
------------------------------
>>> a=5
>>> b=6
>>> a+b
11
>>> a+_                   //最后的表达式赋给_
16
>>> 
---------------------------------
>>> round(4.56,1)
4.6
>>> round(4.4533,2)     //四舍五入,2代表小数点的个数。
4.45
>>> 
--------------------------
>>> print('c:\some\name')
c:\some
ame
>>> print(r'c:\some\name')        //r消除\的转义功能。
c:\some\name
>>> 
--------------------------------
>>> 3*'im'+'ium'            //字符串前面用num* 表示字符串出现几次。
'imimimium'
>>> 
----------------------------
>>> 'im'*3+'ium'          //字符串后面面用*num 表示字符串出现几次。
'imimimium'
>>> 
-----------------------------
>>> 'py''thon'           //字符串自动连接,如果字符串赋给其他变量了,需要+号连接。
'python'
>>> 
-----------------------
>>> text=('kdhaksdkdkgkdk'      //可以用来打断长的字符串
      'ksdgkskdk')
>>> text
'kdhaksdkdkgkdkksdgkskdk'
>>> 
--------------------------
>>> word='python'
>>> word[-6]            //按角标索引
'p'
-------------------------
>>> word[42]            //角标越界
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    word[42]
IndexError: string index out of range
>>> word[2:42]              //列表索引不会越界
'thon'
>>> word[42:]
''
>>> 
-------------------------------
>>> word[0]='y'                       //字符串是不可变数据类型
Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    word[0]='y'
TypeError: 'str' object does not support item assignment
>>> 
--------------------------------
>>> lists=[3,4,5,7]
>>> lists+[3,4,5]           //添加一个列表
[3, 4, 5, 7, 3, 4, 5]
>>> lists.append(5)          //添加一个元素
>>> lists
[3, 4, 5, 7, 5]
>>> 
----------------------------------
>>> a=['d','e']
>>> b=[3,4,5]
>>> c=[a,b]              //列表元素为列表,列表嵌套(nested)
>>> c[0]
['d', 'e']
>>> 
---------------------------------
>>> for i in range(1,20,2):         //range的用法,起点,终点,步长。
print(i)
----------------------------------
>>> for i in range(10):
for j in range(3):
if i>3:
print("break loop")
break                    //break跳出本层循环
else:
print(i,j)



0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
break loop
break loop
break loop
break loop
break loop
break loop
>>> 
-----------------------------------
>>> for i in range(4):
if i%2==0:
print("the times of two",i)
continue                   //结束本次语句执行。
print("not the times of two",i)



the times of two 0
not the times of two 1
the times of two 2
not the times of two 3
>>> 
----------------------------------
>>> list(range(3,6))
[3, 4, 5]
>>> list(range([3,6]))
Traceback (most recent call last):
  File "<pyshell#81>", line 1, in <module>
    list(range([3,6]))
TypeError: 'list' object cannot be interpreted as an integer
>>> list(range(*[3,6]))           //*list,可以解压,unpacking.
[3, 4, 5]
>>> 
-------------------------------------
>>> def my_function():
"""
         nothing              //解释放在函数第一行,作为文档。
         """
pass


>>> print(my_function.__doc__)


         nothing
         
>>> 
---------------------------------------
>>> stack=[3,4,5]            //将列表作为堆。
>>> stack.append(6)
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> 
-----------------------------------------
>>> from collections import deque        //导入模块collection,封装列表称为队列。
>>> queue=deque([3,4,5])
>>> queue.append(6)
>>> queue.popleft()
3
>>> 
----------------------------------------
>>> matrix = [
    [1, 2, 3, 4],
   [5, 6, 7, 8],
   [9, 10, 11, 12],
 ]
>>> 
>>> list(zip(*matrix))   //行转列,元素变为元组
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
>>> 
--------------------------------------
>>> a=[3,4,5]
>>> del(a[0])       //删除。
>>> a
[4, 5]
>>> 
----------------------------------------
>>> t=345,43,'45kd'      //元组,不可变类型
>>> t
(345, 43, '45kd')
>>> t,'ekg'               //添加元素
((345, 43, '45kd'), 'ekg')
>>> 
--------------------------------
>>> sets={'4','5'}
>>> sets={4,5}
>>> sets
{4, 5}


>>> a=set("kdskkskdkkkdksals")  //集合不含重复元素,集合可以进行 - | & ^  操作
>>> a
{'s', 'a', 'k', 'l', 'd'}
>>> 'a' in a       //进行判断
True
>>> b=['a','b']     //列表也可以进行判断。
>>> 'b' in b
True
>>> 
------------------------------------
>>> tel={'jack':4098,'scape':4139}   //字典
>>> tel['guin']=4127
>>> tel
{'guin': 4127, 'jack': 4098, 'scape': 4139}
>>> del tel['guin']
>>> tel
{'jack': 4098, 'scape': 4139}
>>> list(tel.keys())
['jack', 'scape']
>>> for k,v in tel.items():
print(k,v)



jack 4098
scape 4139
>>> tel['jack']+=1       //通过键给值加1
>>> tel
{'jack': 4099, 'scape': 4139}
>>> 
------------------------------------
>>> for i,v in enumerate(['li','ya','fei']):   //迭代,取出元素,第一个元素为脚标
print(i,v)



0 li
1 ya
2 fei
>>> 
---------------------------------------------
>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print('What is your {0}?  It is {1}.'.format(q, a))   //{}占位,里面为角标。
...
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.


-------------------------------------------------------
>>> (1,2,3)<(1,2,4)        //序列之间的比较。
True
>>> 'abc'<'c'
True
>>> 'abc'<'a'
False
>>> (1,3)<(1,3,4)
True
>>> 
---------------------------------------------
>>> a={'jack': 4099, 'scape': 4139,'ama':3095}   //取出a的键,将会被重排。
>>> b=a.keys()
>>> b
dict_keys(['ama', 'jack', 'scape'])
>>> b
---------------------------------------------------------------------------------------
6.1.1
if __name__=="__main__"   //函数入口
------------------------------------
sound/                          Top-level package      //包命名方式
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...


------------------------------------------
import sound.effects.echo        //导入模块
from sound.effects import echo
from sound.effects.echo import echofilter
--------------------------------------------------------------------------------------
7.input and output
>>> s="hello world"
>>> str(s)
'hello world'
>>> repr(s)
"'hello world'"
>>> a=34
>>> s+34
>>> s+repr(a)    //将整形转换为字符串类型进行相连。
'hello world34'
>>> 
-----------------------------
>>> repr(5).rjust(3)        //5占三位 右对齐。ljust,center
'  5'
>>> 
-------------------------
for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))  //2d,3d,4d,表示栈顶位数。
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
...
------------------------------
>>> repr(5).zfill(3)          //填满
'005'
>>> 
-------------------------------
f = open('workfile', 'w')   //打开文件
for line in f:
    print(line,end='')       //没次打印一行,打印完。
------------------------------
>>> import json                    //将内容封装成json(javascript objec notation)形式
>>> json.dumps([1,'simple','list'])
'[1, "simple", "list"]'
----------------------------------------------------------------------------------
8 error and exception


while True:
    try:
        x=int(a)
        break
    except valueError:    //处理异常
        print("oops!")
---------------------------------------
>>> raise NameError('HiThere')  //触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: HiThere


-------------------------------------


class Error(Exception):       自定义异常
    """Base class for exceptions in this module."""
    pass


class InputError(Error):
    """Exception raised for errors in the input.


    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """


    def __init__(self, expression, message):   异常信息
        self.expression = expression
        self.message = message


class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.


    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """


    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message
---------------------------------------------------------------------------------------
9  classes


--------------------------------------------------------------------------------------
10 brife tour of the standard library


>>> math.cos(math.pi/4)       //cos函数,里面有常量math.pi
0.7071067811865476
>>> 
>>> math.log(1024,2)        //对数函数
10.0
>>> 
------------------------------  
import random   #产生随机数
import statistics  #统计,可以求均值方差等。


--------------------------------
from urllib.request import urlopen  //获得网络连接。
with urlopen('http://www.baidu.com') as response:    //将获得的内容放到response中。
for line in response:
line=line.decode('utf-8')
print(line)
---------------------------------------------------------------------------------------
11. Brief Tour of the Standard Library — Part II


>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))  //简短的显示
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"
-----------------------------------
import pprint
pprint.pprint(list,width=30)  //更清晰的显示
----------------------------------
import textwrap
print(textwrap.fill(doc, width=40))  //根据显示屏的大小显示
----------------------------------------
import locale   //对格式分组
----------------------------------------
>>> import time, os.path
>>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
>>> class BatchRename(Template):   //模板方法设计
...     delimiter = '%'            //%占位符
>>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')  //输入
Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f      输入重命名的名字


>>> t = BatchRename(fmt)
>>> date = time.strftime('%d%b%y')    
>>> for i, filename in enumerate(photofiles):    //迭代重命名
...     base, ext = os.path.splitext(filename)
...     newname = t.substitute(d=date, n=i, f=ext)
...     print('{0} --> {1}'.format(filename, newname))


img_1074.jpg --> Ashley_0.jpg
img_1076.jpg --> Ashley_1.jpg
img_1077.jpg --> Ashley_2.jpg
--------------------------------------
Multi-threading        //多线程





































































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值