首页 > 代码库 > python学习笔记

python学习笔记

 

11/28整理

Python的编写要求

[root@ht ~]# which python

/usr/bin/python

[root@ht ~]# vim ~/python/helloworld.py

#!/usr/bin/python

 

print "Hello World!"

Python程序的运行

[root@ht ~]# cd ~/python/

[root@ht python]# python helloworld.py

Hello World!

[root@ht python]# chmod a+x helloworld.py

[root@ht python]# ./helloworld.py

Hello World!

 

[root@ht python]# vim helloworld.py

#!/usr/bin/env python      

#不确定是否是源码安装,还是apt安装。

                       #所以调Python的环境来解读代码

print "Hello World!"

 

根据自己的功能导入标准库

[root@ht python]# python -c "print ‘hello world‘"           #run python script sent in as cmd string

hello world

[root@ht python]# python

Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> dir()

[‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]                #目前内存空间有四个变量值

>>> dir(__builtins__)

[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘Ellipsis‘, ‘EnvironmentError‘, ‘Exception‘, ‘False‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘None‘, ‘NotImplemented‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘True‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘ZeroDivisionError‘, ‘_‘, ‘__debug__‘, ‘__doc__‘, ‘__import__‘, ‘__name__‘, ‘__package__‘, ‘abs‘, ‘all‘, ‘any‘, ‘apply‘, ‘basestring‘, ‘bin‘, ‘bool‘, ‘buffer‘, ‘bytearray‘, ‘bytes‘, ‘callable‘, ‘chr‘, ‘classmethod‘, ‘cmp‘, ‘coerce‘, ‘compile‘, ‘complex‘, ‘copyright‘, ‘credits‘, ‘delattr‘, ‘dict‘, ‘dir‘, ‘divmod‘, ‘enumerate‘, ‘eval‘, ‘execfile‘, ‘exit‘, ‘file‘, ‘filter‘, ‘float‘, ‘format‘, ‘frozenset‘, ‘getattr‘, ‘globals‘, ‘hasattr‘, ‘hash‘, ‘help‘, ‘hex‘, ‘id‘, ‘input‘, ‘int‘, ‘intern‘, ‘isinstance‘, ‘issubclass‘, ‘iter‘, ‘len‘, ‘license‘, ‘list‘, ‘locals‘, ‘long‘, ‘map‘, ‘max‘, ‘min‘, ‘next‘, ‘object‘, ‘oct‘, ‘open‘, ‘ord‘, ‘pow‘, ‘print‘, ‘property‘, ‘quit‘, ‘range‘, ‘raw_input‘, ‘reduce‘, ‘reload‘, ‘repr‘, ‘reversed‘, ‘round‘, ‘set‘, ‘setattr‘, ‘slice‘, ‘sorted‘, ‘staticmethod‘, ‘str‘, ‘sum‘, ‘super‘, ‘tuple‘, ‘type‘, ‘unichr‘, ‘unicode‘, ‘vars‘, ‘xrange‘, ‘zip‘]

>>> import math

>>> dir()

[‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘math‘]

>>> dir(math)

[‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘acos‘, ‘acosh‘, ‘asin‘, ‘asinh‘, ‘atan‘, ‘atan2‘, ‘atanh‘, ‘ceil‘, ‘copysign‘, ‘cos‘, ‘cosh‘, ‘degrees‘, ‘e‘, ‘exp‘, ‘fabs‘, ‘factorial‘, ‘floor‘, ‘fmod‘, ‘frexp‘, ‘fsum‘, ‘hypot‘, ‘isinf‘, ‘isnan‘, ‘ldexp‘, ‘log‘, ‘log10‘, ‘log1p‘, ‘modf‘, ‘pi‘, ‘pow‘, ‘radians‘, ‘sin‘, ‘sinh‘, ‘sqrt‘, ‘tan‘, ‘tanh‘, ‘trunc‘]

>>> math.floor(4.7)

4.0

>>> help(math.floor)                           #一般开两个控制台,一个用help来查看帮助文档

Help on built-in function floor in module math:

 

floor(...)

    floor(x)

   

    Return the floor of x as a float.

    This is the largest integral value <= x.

(END)

 

>>>  mystring = ‘hello world!‘                   #注意不能缩进不然报错

  File "<stdin>", line 1

    mystring = ‘hello world!‘

    ^

IndentationError: unexpected indent

>>> mystring = ‘hello world!‘

>>> print mystring

hello world!

>>> yourstring = ‘ again ‘

>>> print mystring + yourstring

hello world! again

 

>>> _                                    #表示最后一执行的表达式

4.0

 

格式化字符串

>>> print "%s is number %d! " % ( "python",1)                 #格式化字符串

python is number 1!

>>> print "%d is number, %s is very power!" %(100,"python")

100 is number, python is very power!

>>> template = "Nice to meet %s,you are %d years old."                    #tuples,先创建个模板

>>> print template % ("ht")

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: not enough arguments for format string

>>> print template % ("ht",22)

Nice to meet ht,you are 22 years old.

>>> ht = ("huangteng",22)

>>> print template % ht

Nice to meet huangteng,you are 22 years old.

 

标准输入输出的理解

[root@ht python]# vim sys.stderr.py                      

#!/usr/bin/env python

 

import sys

 

print >> sys.stderr, ‘Standard Err‘

print >> sys.stdout, ‘Standard Output‘

[root@ht python]# python sys.stderr.py

Standard Err

Standard Output

[root@ht python]# python sys.stderr.py 2> /dev/null

Standard Output

[root@ht python]# python sys.stderr.py 1> /dev/null

Standard Err

 

raw_input的输入

>>> aNum = raw_input ( ‘PLS input a number: ‘)                #raw_input,返回的是字符串

PLS input a number: 10

>>> bNum = raw_input ( ‘PLS input b number: ‘)

PLS input b number: 99

>>> print aNum + bNum

1099

>>> type(aNum)

<type ‘str‘>

>>> print int(aNum) + int(bNum)               #类型转化

109

>>> print 5*50

250

>>> print "5" * 50

55555555555555555555555555555555555555555555555555

>>> print "=" * 50                                         #打印50个=

==================================================

 

>>> print "hello world!" #这是注释

hello world!

                                               #定义函数时也有不同的注释 :’’’

>>> def bar():

...     ‘This is inline document of bar. ‘

...     pass

...

>>> help(bar)

Help on function bar in module __main__:

 

bar()

This is inline document of bar.

 

>>> 11 // 3 * 3 + 11 % 3                  #11求倍数再乘以,再加取的余数等于它本身

11

>>> 11 ** 2                                           #求平方

121

>>> 2 ** 4                                             #求四次方

16

 

>>> 1<2

True

>>> 2>3

False

>>> not 2 > 3

True

>>> 3 < 4 and 4 < 5

True

 

>>> y = 2

>>> y *= 5

>>> print y

10

>>> a = 0x7f

>>> print a

127

>>> a = 127

>>> hex(127)

‘0x7f‘

 

>>> myStr = ‘123456789ABCDEF‘

>>> myStr[2:9]

‘3456789‘

>>> myStr[2:9:2]

‘3579‘

>>> myStr[9:2:-2]  #负数表示倒方向跳

‘A864‘

 

>>> myStr[::]

‘123456789ABCDEF‘

>>> myStr[0:len(myStr):]

‘123456789ABCDEF‘

>>> len (myStr)

15

 

>>> alist = [1,2,3,4,5,]                         #方括号表示list,圆括号是tuples,花括号是Dictionaries

>>> print alist                                        #可以自由转换

[1, 2, 3, 4, 5]

>>> alist[1]

2

>>> alist[1:3]

[2, 3]

>>> alist[:-1]

[1, 2, 3, 4]

>>> alist[::-1]

[5, 4, 3, 2, 1]

>>> alist[0] = 100

>>> alist

[100, 2, 3, 4, 5]

>>> class Person():            #类

...     pass

...

>>> ht = Person()

>>> alist [1] = ht

>>> alist

[100, <__main__.Person instance at 0x7f651ec4bdd0>, 3, 4, 5]

>>> blist = [100,1000]

>>> alist[3]=blist

>>> alist

[100, <__main__.Person instance at 0x7f651ec4bdd0>, 3, [100, 1000], 5]

>>> alist[3][1]

1000

 

tuple不支持赋值,赋值前先转换.通过位置来取值

>>> atuple = (1,2,3,4,5,)

>>> atuple

(1, 2, 3, 4, 5)

>>> type(atuple)

<type ‘tuple‘>

>>> atuple [3]

4      

>>> atuple [1:3]                           #

(2, 3)

>>> atuple [1:2]

(2,)

>>> atuple[2] = [100,1000]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: ‘tuple‘ object does not support item assignment

>>> blist

[100, 1000]

>>> tuple(blist)

(100, 1000)

 

dict字典通过key来取值                                                         

>>> aDict = {‘user‘:‘root‘,‘host‘:‘172.24.18.18‘,‘password‘:‘redhat‘}

>>> aDict

{‘host‘: ‘172.24.18.18‘, ‘password‘: ‘redhat‘, ‘user‘: ‘root‘}

>>> aDict [‘user‘] = ‘student‘

>>> aDict

{‘host‘: ‘172.24.18.18‘, ‘password‘: ‘redhat‘, ‘user‘: ‘student‘}

>>> aDict [‘database‘] = ‘Mysql‘

>>> aDict

{‘host‘: ‘172.24.18.18‘, ‘password‘: ‘redhat‘, ‘user‘: ‘student‘, ‘database‘: ‘Mysql‘}

 

>>> blist = [10,1000,10000,100000,999999]

>>> for el in blist:

...     print el

...

10

1000

10000

100000

999999

 

>>> aDict

{‘host‘: ‘172.24.18.18‘, ‘password‘: ‘redhat‘, ‘user‘: ‘student‘, ‘database‘: ‘Mysql‘}

>>> aDict.keys()

[‘host‘, ‘password‘, ‘user‘, ‘database‘]

>>> aDict.values()

[‘172.24.18.18‘, ‘redhat‘, ‘student‘, ‘Mysql‘]

 

>>> for k in aDict:

...     print k,aDict[k]

...

host 172.24.18.18

password redhat

user student

database Mysql

 

编写for循环Python程序

#!/usr/bin/env python

 

aNum = raw_input(‘PLS input a number: ‘)

aNum = int (aNum)

 

if aNum > 100:

    print "KFC"

else:

print "Fastfood"

[root@ht python]# python first.py

PLS input a number: 23

Fastfood

[root@ht python]# python first.py

PLS input a number: 101

KFC

 

[root@ht python]# vim time.py

#!/usr/bin/env python

 

i = 1

while i < 10:

    print i

    print "=" *i

    i += 1

[root@ht python]# python time.py

1

=

2

==

3

===

4

====

5

=====

6

======

7

=======

8

========

9

=========

>>> randomlist

[3, 6, 78, 23, 80]

>>> for k in randomlist:

...     if k % 2 == 0:

...         print k

...

6

78

80

 

一步到位的列出所需数据

>>> alist = [ k for k in randomlist if k %2 == 0 ]

>>> alist

[6, 78, 80]

 

open()的运用

file_name变量包含我们希望打开的文件的字符串名称,access_mode为‘r‘为读,‘w‘为写,或‘a‘为追加。可以在access_mode字符串中使用的其他标志包括用于双读写访问的“+”和用于二进制访问的“b”。如果没有提供模式,a默认为只读(‘r‘)用于打开文件。

 

如果open()成功,将返回一个文件对象作为句柄(句柄)。所有成功访问此文件必须通过其文件句柄。一旦返回一个文件对象,我们就可以访问另一个功能通过其方法如readlines()和close()。方法是文件对象的属性并且必须通过点属性标记访问(参见下面的CoreNote)。

 

open(...)

    open(name[, mode[, buffering]]) -> file object

   

    Open a file using the file() type, returns a file object.  This is the

preferred way to open a file.

 

读写文件,一行一行读

>>> passwd = open(‘/tmp/passwd‘, ‘r+‘)

>>> passwd.readline()

‘root:x:0:0:root:/root:/bin/bash\n‘

>>> passwd.readline()

‘bin:x:1:1:bin:/bin:/sbin/nologin\n‘

>>> passwd.tell()

183

>>> passwd.readline()

‘sync:x:5:0:sync:/sbin:/bin/sync\n‘

>>> passwd.tell()

215

>>> passwd.readline()

‘root:x:0:0:root:/root:/bin/bash\n‘

>>> passwd.seek(129)

>>> passwd.readline()

‘sbin/nologin\n‘

>>> passwd.tell()

142

>>> passwd.close()

 

 

>>> passwd = open (‘/tmp/passwd‘, ‘rw+‘)

>>> passwd.readline()

‘root:x:0:0:root:/root:/bin/bash\n‘

>>> passwd.seek(80)

>>> passwd.write(‘#############‘)

>>> passwd.readline()

‘bin/nologin\n‘

>>> passwd.readline()

‘adm:x:3:4:adm:/var/adm:/sbin/nologin\n‘

>>> passwd.close()

 

循环的运用

>>> passwd = open(‘/tmp/passwd‘)

>>> for line in passwd:

...     print line + ‘\n‘

...

root:x:0:0:root:/root:/bin/bash

 

 

bin:x:1:1:bin:/bin:/sbin/nologin

使用‘a‘模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。

 

文件模式

解释

r

以只读方式打开

w

以写方式打开,文件不为空时清空文件;文件不存在时新建文件。

a

追加模式,没有则创建

r+,w+,a+

以读写模式打开,参见w,a

 

11/29整理

错误和异常

>>>  mystr = ‘abc‘

  File "<stdin>", line 1

    mystr = ‘abc‘

    ^

IndentationError: unexpected indent

>>> alist = [10,100]

>>> alist[3]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IndexError: list index out of range

>>> adict = {}

>>> adict[‘user‘]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: ‘user‘

>>> tmp = open(‘/tmp/dddd.txt‘,‘r‘)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IOError: [Errno 2] No such file or directory: ‘/tmp/dddd.txt‘

错误异常的处理

#!/usr/bin/env python

 

try:

    adict = {}

    print adict[‘sex‘]                                               #报KeyError的错误

    alist = [10,100]

    print alist[2]                                            #报IndexError的错误

    tmp = open(‘/tmp/abx.txt‘,‘r‘)               #报IoError的错误

    tmp.readlines()

    tmp.close()

#except IOError, e:

#    print "Can‘t open file",e                      #处理报错

#except (IndexError,KeyError) ,e:

#    print "No such index or key"            #处理报错

except :                                                             #忽略所有错误

    pass

print ‘=‘ * 50

[root@ht python]# python try.py

==================================================

 

自定义函数

>>> def addMe2Me(x):

...     ‘‘‘x:x is int. ‘‘‘

...     print x+x

...

>>> addMe2Me(5)

10

>>> a = addMe2Me (5)

10

>>> a

>>> type(a)

<type ‘NoneType‘>

>>> del addMe2Me

自定义函数时return返回值

>>> def addMe2Me (x):

...     ‘‘‘x : x is int.

...     -->: the result of ‘x + x‘ ‘‘‘

...     return x + x

...

>>> a = 5

>>> a = addMe2Me (a)

>>> a

10

type的使用技巧

>>> b = ‘abc‘

>>> b = addMe2Me(b)

>>> b

‘abcabc‘

>>> type(‘‘) == type (b)

True

>>> type(‘‘)

<type ‘str‘>

>>> type (0) == type (a)

True

 

函数的缺省值

有多个参数时缺省参数放最后面

>>> def welcome (people = ‘Unkown‘):

...     print "Nice to meet %s" % people

...

>>> welcome (‘huangteng‘)

Nice to meet huangteng

>>> welcome ()

Nice to meet Unkown

 

其他模块的了解

         time os threading

os里面常用的是

         os.relink()                    #删除

         os.chmod()                 #修改权限。权限必须为四位

 

>>、<<的使用

>>> a = 128

>>> a >>= 2               # 表示a除以2的2次方

>>> a

32

>>> c = 7

>>> c <<= 3               #表示c乘以2的三次方

>>> c

56

 

二进制下的与或非

>>> c = 11

>>> c |= 5

>>> c

15

与的权限位的利用

>>> auser = 11

>>> buser = 9

>>> write_permission = 2

>>> if auser & write_permission == write_permission:

...     print "writeable"

...

writeable

>>> if buser & write_permission == write_permission:

...     print "writeable"

... else:

...     print "Can‘t write"

...

Can‘t write

取反的运用,相减

>>> a = 3

>>> a ^= 255

>>> a

252

>>> a = 17

>>> a ^= 255

>>> a

238

 

内存指向

(相同的int类型值,指向也相同)640k以内的内存指向

>>> x = y = z = 1

>>> id(x),id(y),id(z)

(20464440, 20464440, 20464440)

>>> a = b = c = ‘xyz‘

>>> id(a),id(b),id(c)

(140340466543232, 140340466543232, 140340466543232)

>>> z += 1

>>> x += 1

>>> d = 2

>>> id(x), id(y), id(z),id(d)

(20464416, 20464440, 20464416, 20464416)

 

 

自定义模板的编写体验

#!/usr/bin/env python

 

""" This is a demo moudle

    author:zing1024@126.com

"""

 

import sys

import os

 

def addMe2Me(x):

    if type(x) == type(0):

        return x + x

    else:

        return 0

 

 

print addMe2Me (100)               #自己测试

print "=" * 50

print addMe2Me (‘abc‘)

运行程序的返回如下

[root@ht python]# python test.py

200

==================================================

0

接下来导入模块的话,会自己执行该模块里的代码,如下

[root@ht ~]# cd python/

[root@ht python]# python

Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import test

200

==================================================

0

解决以上的问题

 

""" This is a demo moudle

    author:zing1024@126.com

"""

 

import sys

import os

 

def addMe2Me(x):

    if type(x) == type(0):

        return x + x

    else:

        return 0

 

if ‘__main__‘ == __name__:

 

    print addMe2Me (100)

    print "=" * 50

print addMe2Me (‘abc‘)

>>> import test

>>> dir(test)

[‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘addMe2Me‘, ‘os‘, ‘sys‘]

 

空即是空

>>> a = None

>>> None == True

False

>>> None == False

False

>>> None == None

True

>>> a is None

True

 

is、浮点值的运用

>>> foo1 = 4.3

>>> foo2 = foo1

>>> id(foo1),id(foo2)

(36816376, 36816376)

>>> foo1 is foo2

True

 

cmp的比较大于是1,小于是-1,等于是0

>>> a = ‘abc‘

>>> b = ‘abcd‘

>>> cmp(a,b)

-1

>>> c = ‘accd‘

>>> cmp(b,c)

-1

>>> cmp(c,b)

1

>>> d = ‘abc‘

>>> cmp(a,d)

0

repr出来的是字符串

>>> alist  = [10,24,111,45]

>>> repr(alist)

‘[10, 24, 111, 45]‘

>>> type(repr(alist))

<type ‘str‘>

>>> repr (2016)

‘2016‘

>>> str(‘abc‘)

‘abc‘

>>> repr(‘abc‘)

"‘abc‘"

 

判断对象类型

>>> a

‘abc‘

>>> isinstance(a,str)

True

>>> alist = [10,287,67]

>>> isinstance(alist,str)

False

>>> isinstance(alist,list)

True

 

11/30整理

atuple转换到list

>>> atuple = (10,24,7)

>>> list(atuple)

[10, 24, 7]

>>> tmplist = list (atuple)

>>> tmplist[1] = 30

>>> tmplist

[10, 30, 7]

>>> atuple = tuple(tmplist)

>>> atuple

(10, 30, 7)

 

指针指向内存的不同段,list的id不变

>>> alist = [‘other‘,86,2,‘man‘]

>>> id(alist)

139798990940856

>>> alist[1] += 1

>>> id(alist)                                  #里面的单个数据的id会变

139798990940856

>>> alist

[‘other‘, 87, 2, ‘man‘]

 

bool类型的理解,直接利用0来表示false

>>> bool(1)

True

>>> bool(100)

True

>>> bool(0)

False

>>> 0 is False

False

>>> a = 0

>>> if a :

...     print "True"

... else:

...     print "False"

...

False

>>> a = 100

>>> if a :

...     print "True"

... else:

...     print "False"

...

True

 

bool判断其他类型的true、false的直接运用

>>> alist = []

>>> bool(alist)

False

>>> if alist:

...     print "has elements"

... else:

...     print "Empty list"

...

Empty list

 

>>> alist.append(‘abc‘)

>>> if alist:

...     print "has elements "

... else:

...     print "empty list"

...

has elements

 

重点语句:random.randint

>>> import random

>>> alist = [random.randint(1,40) for e in range(10)]

>>> alist

[20, 6, 35, 27, 29, 19, 3, 12, 34, 29]

 

enumerate生成可罗列的对象

>>> alist

[20, 6, 35, 27, 29, 19, 3, 12, 34, 29]

>>> enumerate(alist)

<enumerate object at 0x7f89650eadc0>

>>> e = enumerate(alist)

>>> e.next()

(0, 20)

>>> e.next()

(1, 6)

>>> e.next()

(2, 35)

 

排序

>>> alist

[20, 6, 35, 27, 29, 19, 3, 12, 34, 29, 19]

>>> sorted(alist)

[3, 6, 12, 19, 19, 20, 27, 29, 29, 34, 35]

>>> sorted(alist,reverse=True)                     #倒序

[35, 34, 29, 29, 27, 20, 19, 19, 12, 6, 3]

>>> blist = [ random.randint(1,80) for i in range(7) ]

>>> blist

[22, 40, 21, 4, 27, 36, 10]

>>> blist.sort(reverse=True)

>>> blist

[40, 36, 27, 22, 21, 10, 4]

 

zip的运用

zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。

 

>>> blist = [ random.randint(1,80) for i in range(7) ]

>>> clist = [ random.randint(1,190) for i in range(5) ]

>>> alist = [ random.randint(1,40) for i in range(11) ]

>>> zip (alist,blist,)

[(12, 32), (18, 74), (30, 45), (17, 22), (33, 11), (16, 74), (3, 28)]

>>> zip (blist,clist)

[(32, 71), (74, 54), (45, 32), (22, 168), (11, 24)]

>>> zip (alist,blist,clist)

[(20, 32, 71), (6, 74, 54), (35, 45, 32), (27, 22, 168), (29, 11, 24)]

 

zip整合list为{}

>>> keylist = [‘name‘,‘height‘,‘weight‘,‘sex‘]

>>> valuelist = [‘huangteng‘,178,124,‘male‘]

>>> ht = dict( zip(keylist,valuelist))

>>> ht

{‘sex‘: ‘male‘, ‘name‘: ‘huangteng‘, ‘weight‘: 124, ‘height‘: 178}

 

list.pop()弹出最后一位数据

>>> alist

[12, 18, 30, 17, 33, 16, 3, 5, 40, 26, 22]

>>> alist.pop()

22

>>> alist.pop()

26

 

zip的再运用

>>> ad = dict(   zip (alist,blist)   )

>>> ad

{33: 11, 3: 28, 12: 32, 16: 74, 17: 22, 18: 74, 30: 45}

>>> ad = dict(     zip (  range(len(alist)),alist )   )

>>> ad

{0: 12, 1: 18, 2: 30, 3: 17, 4: 33, 5: 16, 6: 3, 7: 5, 8: 40}

 

join的衔接

>>> blist = [‘root‘,‘0‘,‘/root‘,‘/bin/sh‘]

>>> ‘:‘.join(blist)

‘root:0:/root:/bin/sh‘

>>> ‘===‘.join(blist)

‘root===0===/root===/bin/sh‘

 

endswith和startswith的运用

>>> import socket

>>> alist = [fn for fn in dir(socket) if fn.startswith(‘SOCK_‘)]

>>> alist

[‘SOCK_DGRAM‘, ‘SOCK_RAW‘, ‘SOCK_RDM‘, ‘SOCK_SEQPACKET‘, ‘SOCK_STREAM‘]

>>> blist = [ e for e in alist if e.endswith(‘RAW‘)]

>>> blist

[‘SOCK_RAW‘]

 

字符的了解

#!/usr/bin/env python

# coding: utf-8

 

print "hello world!"

print u‘你好!‘

[root@ht python]# python zifu.py

hello world!

你好!

 

 

>>> a = 100

>>> print "|%10d|" %a

|       100|

>>> print "|%-10d|" %a

|100       |

>>> import math

>>> print "%f" % math.pi

3.141593

>>> print "%f15" % math.pi

3.14159315

 

裸字符串

>>> mystr = ‘c:\windows\news\tables‘

>>> print mystr

c:\windows

ews   ables

>>> mystr = r‘c:\windows\news\tables‘

>>> print mystr

c:\windows\news\tables

 

切割split的运用

列表转字符串,利用join

切割字符串,利用split

>>> userinfo = ‘student:x:501:501::/home/student:/bin/sh‘

>>> userinfo.split(‘:‘)

[‘student‘, ‘x‘, ‘501‘, ‘501‘, ‘‘, ‘/home/student‘, ‘/bin/sh‘]

>>> useril = userinfo.split(‘:‘)

>>> ‘:‘.join(useril)

‘student:x:501:501::/home/student:/bin/sh‘

 

利用hashlib库生成密码

>>> import hashlib

>>> m = hashlib.md5()

>>> m.update(mystr)

>>> m

<md5 HASH object @ 0x7f89650f8bb8>

>>> print m.hexdigest()

65c9f021e55c8d62c2e39b6c7d797fa5

 

编写自己的sort模块

#!/usr/bin/env python

#Ascending --> [‘ef‘,‘hi‘,‘kk‘,‘abc‘]

#Desceding --> [‘abc‘,‘kk‘,‘hi‘,‘ef‘]

 

def my_cmp(a,b):

    if len(a) > len(b):

        return 1

    elif len(a) < len(b):

        return -1

    else:

        return cmp(a,b)

 

alist = [‘abc‘,‘ef‘,‘kk‘,‘hi‘,]

alist.sort(my_cmp)

print repr(alist)

[root@ht python]# python mysort.py

[‘ef‘, ‘hi‘, ‘kk‘, ‘abc‘]

深入的编写people的比较模块

#!/usr/bin/env python

 

def sort_age(a,b):

    return cmp(a[‘age‘],b[‘age‘])

def sort_height(a,b):

    return cmp(a[‘height‘],b[‘height‘])

def sort_weight(a,b):

    return cmp(a[‘weight‘],b[‘weight‘])

 

ht = { ‘name‘:‘huangteng‘,‘age‘:22,‘height‘:178,‘weight‘:124,}

lz = { ‘name‘:‘lizhi‘,‘age‘:38,‘height‘:174,‘weight‘:146,}

zjl = { ‘name‘:‘zhoujielun‘,‘age‘:36,‘height‘:175,‘weight‘:138,}

 

people = [ht,lz,zjl]

people.sort(sort_age,reverse=True)   #倒序输出,以年龄排序的列,自行测试其他两个排序方法

print repr(people)

 

[root@ht python]# python agesort.py

[{‘age‘: 38, ‘name‘: ‘lizhi‘, ‘weight‘: 146, ‘height‘: 174}, {‘age‘: 36, ‘name‘: ‘zhoujielun‘, ‘weight‘: 138, ‘height‘: 175}, {‘age‘: 22, ‘name‘: ‘huangteng‘, ‘weight‘: 124, ‘height‘: 178}]

 

12/1整理

tuple中可以接逗号(,)的解释

>>> atuple = (1)

>>> type (atuple)

<type ‘int‘>

>>> atuple = (1,)

>>> type (atuple)

<type ‘tuple‘>

 

tuple中的索引查找

>>> atuple = tuple([ random.randint(1,80) for i in range(10)])

>>> atuple

(47, 77, 48, 58, 37, 30, 73, 34, 15, 66)

>>> atuple.index(47)

0

 

一维list:修改cp后的list数据,原list不变

>>> plist = [22,‘huangteng‘,178,124]

>>> cplist = plist[:]

>>> id(plist),id(cplist)

(140446579381024, 140446579352136)

>>> cplist

[22, ‘huangteng‘, 178, 124]

>>> cplist[1] = ‘lizhi‘

>>> cplist

[22, ‘lizhi‘, 178, 124]

>>> plist

[22, ‘huangteng‘, 178, 124]

 

 

二维list的shallow复制和理解

>>> del plist

>>> plist = [22,[‘localtion‘,‘ChangSha‘],178,‘huangteng‘]

>>> cplist = plist[:]

>>> cplist

[22, [‘localtion‘, ‘ChangSha‘], 178, ‘huangteng‘]

>>> cplist[1][1] = ‘HengYang‘                              #修改复制后的list,原数据也会跟着变

>>> cplist

[22, [‘localtion‘, ‘HengYang‘], 178, ‘huangteng‘]

>>> plist

[22, [‘localtion‘, ‘HengYang‘], 178, ‘huangteng‘]

解释如下:

>>> import copy

>>> oplist = [22,[‘localtion‘,‘tianshi‘],178,‘male‘,‘huangteng‘,]

>>> normalcopy = oplist[:]

>>> normalcopy = list(oplist)

>>> normalcopy

[22, [‘localtion‘, ‘tianshi‘], 178, ‘male‘, ‘huangteng‘]

>>> id(oplist[0]),id(normalcopy[0])

(9703744, 9703744)

>>> normalcopy[0] += 1  #修改数据后内存指向不同,所以复制后的list和原list的数据也不同

>>> id(oplist[0]),id(normalcopy[0])

(9703744, 9703720)

>>> id(oplist[1]),id(normalcopy[1])  #二维list的内存指向也相同

(140446579407976, 140446579407976)

>>> normalcopy[1][1] = ‘shanghai‘  #修改二维list里面的数据

>>> id(oplist[1]),id(normalcopy[1])  #内存指向还没变,所以原list和复制后的list进行数据同步

(140446579407976, 140446579407976)

>>> normalcopy

[23, [‘localtion‘, ‘shanghai‘], 178, ‘male‘, ‘huangteng‘]

>>> oplist

[22, [‘localtion‘, ‘shanghai‘], 178, ‘male‘, ‘huangteng‘]

 

 

deep copies的理解

>>> dcopy = copy.deepcopy(oplist)

>>> oplist

[22, [‘localtion‘, ‘shanghai‘], 178, ‘male‘, ‘huangteng‘]

>>> dcopy

[22, [‘localtion‘, ‘shanghai‘], 178, ‘male‘, ‘huangteng‘]

>>> id(oplist),id(dcopy)                                         #查看到内存指向不同,结合上面对shallow的分析

(140446469090264, 140446579352136)           #id不同的话,复制后的,数据操作互不受影响

>>> dcopy[1][1] = ‘BeiJing‘

>>> dcopy

[22, [‘localtion‘, ‘BeiJing‘], 178, ‘male‘, ‘huangteng‘]

>>> oplist

[22, [‘localtion‘, ‘shanghai‘], 178, ‘male‘, ‘huangteng‘]

 

 

>>> help({}.fromkeys)

 

Help on built-in function fromkeys:

fromkeys(...)

    dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.

v defaults to None.

>>> one = {}.fromkeys(keylist)

>>> one

{‘sex‘: None, ‘name‘: None, ‘weight‘: None, ‘height‘: None}

>>> one[‘sex‘]            #没有值,也不会报错

>>> one = {}.fromkeys(keylist,‘unknown‘)                  #设置缺省值

>>> one

{‘sex‘: ‘unknown‘, ‘name‘: ‘unknown‘, ‘weight‘: ‘unknown‘, ‘height‘: ‘unknown‘}

>>> one.keys()                   #list的取键值

[‘sex‘, ‘name‘, ‘weight‘, ‘height‘]

>>> one.values()                #取values值

[‘unknown‘, ‘unknown‘, ‘unknown‘, ‘unknown‘]

>>> dict (zip(one.keys(),one.values()))               #折腾的转来转去

{‘height‘: ‘unknown‘, ‘name‘: ‘unknown‘, ‘weight‘: ‘unknown‘, ‘sex‘: ‘unknown‘}

 

get()不报错的使用

>>> help(ht.get)

get(...)

    D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.

>>> ht

{‘sex‘: ‘male‘, ‘name‘: ‘huangteng‘, ‘weight‘: 124, ‘height‘: 178}

>>> ht.get(‘localtion‘)                  #即使没有也不报错

>>> 

 

取字符串,并一一对应

>>> mystr = ‘hello world!‘

>>> mydict = dict([(i+1,mystr[i]) for i in range(len(mystr))])

>>> mydict

{1: ‘h‘, 2: ‘e‘, 3: ‘l‘, 4: ‘l‘, 5: ‘o‘, 6: ‘ ‘, 7: ‘w‘, 8: ‘o‘, 9: ‘r‘, 10: ‘l‘, 11: ‘d‘, 12: ‘!‘}

 

Dict的复制

>>> copy_zgr = dict(**zgr)

>>> id(copy_zgr),id(zgr)

(10320368, 11165168)

>>> id(copy_zgr[‘sex‘]),id(zgr[‘sex‘])

(140446579402048, 140446579402048)           #二维下类似于shallow copy

>>> copy_zgr[‘sex‘] = ‘female‘

>>> zgr

{‘sex‘: ‘male‘, ‘name‘: ‘leslie‘, ‘weight‘: 128, ‘height‘: 176}

 

items()等同于zip keys和values

>>> zgr.items()

[(‘sex‘, ‘male‘), (‘name‘, ‘leslie‘), (‘weight‘, 128), (‘height‘, 176)]

>>> zip(zgr.keys(),zgr.values())

[(‘sex‘, ‘male‘), (‘name‘, ‘leslie‘), (‘weight‘, 128), (‘height‘, 176)]

 

set去重

>>> alist = [ random.randint(1,50) for i in range(15)]

>>> alist

[34, 7, 46, 6, 32, 16, 40, 37, 17, 17, 5, 19, 42, 50, 36]

>>> list(set(alist))

[32, 34, 36, 37, 6, 7, 40, 42, 46, 16, 17, 50, 19, 5]

 

 

>>> alist = [ random.randint(1,50) for i in range(7)]

>>> alist

[7, 26, 37, 27, 7, 41, 9]

>>> blist = alist[3:]

>>> blist.append(23)

>>> blist.append(34)

>>> blist

[27, 7, 41, 9, 23, 34]

>>> alist

[7, 26, 37, 27, 7, 41, 9]

>>> aset = set(alist)

>>> bset = set(blist)

>>> aset & bset                           #取交集的值

set([41, 27, 9, 7])

>>> aset | bset                              #取合集的值

set([34, 37, 7, 9, 23, 41, 26, 27])

>>> aset – bset                             #aset取减完交集后的值

set([26, 37])

>>> aset ^ bset                             #取反(交集的反)

set([34, 37, 26, 23])

 

>>> aset.difference(bset)                             #同-   注意区别      .difference_update()

set([26, 37])

>>> aset.symmetric_difference(bset)                 #同^                            

set([34, 37, 26, 23])

>>> aset.intersection(bset)                           #同&                          

set([41, 27, 9, 7])

 

set的update()只更新没有的

>>> aset

set([37, 7, 41, 9, 26, 27])

>>> aset.update([37,26,‘abc‘])

>>> aset

set([‘abc‘, 37, 7, 41, 9, 26, 27])

>>> aset.pop()                    #从前面往后面弹出

‘abc‘

>>> aset.pop()

37

 

set的remove和discard删除

>>> aset = set(alist)

>>> aset

set([37, 7, 41, 9, 26, 27])

>>> aset.remove(9)

>>> aset.remove(9)

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

KeyError: 9

>>> aset.discard(26)

>>> aset.discard(26)         #不报错

 

 

update改变自身的值

>>> aset

set([37, 7, 41, 27])

>>> bset

set([34, 7, 41, 9, 23, 27])

>>> aset.difference_update(bset)                        # - 的同时并改变自己

>>> aset

set([37])

>>> aset.symmetric_difference_update(bset)   # |取合集的同时并更新自己

>>> aset

set([34, 37, 7, 41, 23, 9, 27])

>>> aset.intersection_update(bset)                     #去掉自己的不同后,取交集

>>> aset

set([34, 7, 41, 9, 23, 27])

 

if…else的重点句型

>>> x = 10

>>> y = 9

>>> bigger = x if x > y else y

>>> bigger

10

 

 

while语句的理解

>>> while i < 100:

...     if i % 5:

...         i += 1

...         continue

...     else:

...         i +=1

... else:

...     print i                               #i < 100不满足后打印

...

100

 

 

iter可罗列对象

>>> alist

[7, 26, 37, 27, 7, 41, 9]

>>> alist.next()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

AttributeError: ‘list‘ object has no attribute ‘next‘

>>> it = iter(alist)

>>> it

<listiterator object at 0x7ff82b28c2d0>

>>> it.next()

7

>>> it.next()

26

 

next()的进一步运用

>>> def get_random(num):

...     randlist = [ random.randint(1,80) for i in range(num)]

...     while len(randlist):

...         yield randlist.pop()

...

>>> gr = get_random(5)

>>> a = gr.next()

>>> a

32

>>> a = gr.next()

>>> a

77

 

map、lambda的列表解析

>>> alist

[7, 26, 37, 27, 7, 41, 9]

>>> blist

[27, 7, 41, 9, 23, 34]

>>> blist.append(87)

>>> blist

[27, 7, 41, 9, 23, 34, 87]                                #作为表达式,lambda返回一个值(即一个新的函数)。

>>> result = map(lambda x,y : x if x > y else y,alist,blist)

>>> result

[27, 26, 41, 27, 23, 41, 87]

 

12/2整理

筛选下列里的奇数(filter)

>>> import random

>>> alist = [ random.randint(1,50) for i in range(10)]

>>> alist

[9, 22, 10, 41, 11, 15, 49, 24, 21, 39]

>>> def odd(x):

...     return x % 2

...

>>> oddlist = filter(odd,alist)

>>> oddlist

[9, 41, 11, 15, 49, 21, 39]

同下

>>> oddlist = filter(lambda x : x % 2,alist)                           #求奇数

>>> oddlist

[9, 41, 11, 15, 49, 21, 39]

>>> [ x for x in alist if x % 2]

[9, 41, 11, 15, 49, 21, 39]

>>> oddlist = filter(lambda x : x % 2 == 0,alist)                 #求偶数

>>> oddlist

[22, 10, 24]

 

找出文件中的特定用户(filter)

>>> passwd = open(‘/etc/passwd‘,‘r‘)

>>> users = [ filter(lambda line : line.endswith(‘sh\n‘), passwd.readlines())]       #记得换行\n

>>> users

[[‘root:x:0:0:root:/root:/bin/bash\n‘, ‘student:x:500:500::/home/student:/bin/bash\n‘, ‘mysql:x:501:501::/home/mysql:/bin/bash\n‘]]

 

寻找字数最长的一行

>>> passwd = open(‘/etc/passwd‘,‘r‘)         

>>> longest = max(len(x.strip()) for x in passwd)

>>> longest

89

 

不同系统兼容写法

>>> os.curdir + os.sep + ‘myfile‘

‘./myfile‘

>>> os.linesep

‘\n‘

>>> repr(os.linesep)

"‘\\n‘"

>>> os.sep

‘/‘

>>> os.pathsep

‘:‘

>>> os.curdir

‘.‘

>>> os.pardir

‘..‘

 

命令行写入文件

#!/usr/bin/env python

import os

import sys

 

ends = [ ‘quit‘,‘exit‘,]

filename = raw_input(‘Enter a filename: ‘)

f = open(filename,‘w‘)

 

while True:

    aline = raw_input()

    if aline in ends:

        break

    else:

        f.write("%s\n" % aline)

f.close()

 

Python写到另一个控制台

>>> f = open(‘/etc/passwd‘)

>>> tty = open(‘/dev/pts/1‘,‘w+‘)

>>> for line in f:

...     tty.write(line)

...

>>> f.isatty()

False

>>> tty.isatty()

True

 

Sys.argv[]是用来获取命令行参数

sys.argv[0]表示代码本身文件路径,所以参数从1开始

#!/usr/bin/env python

 

import os

import sys

 

if len(sys.argv) > 5:

    print sum(map(int,sys.argv[1:]))                  #int类型的加法运算

else:

print "Not enough"

 

os的stat的了解

>>> os.stat(‘/etc/passwd‘)

posix.stat_result(st_mode=33188, st_ino=150707, st_dev=64768L, st_nlink=1, st_uid=0, st_gid=0, st_size=1867, st_atime=1480606576, st_mtime=1480520080, st_ctime=1480520080)

>>> os.stat(‘/etc/passwd‘).st_size

1867

>>> os.stat(‘/etc/passwd‘).st_atime

1480606576.855361

>>> import time

>>> atime = os.stat(‘/etc/passwd‘).st_atime

>>> time.ctime(atime)

‘Thu Dec  1 23:36:16 2016‘

 

isfile和isdir的判断

>>> os.listdir(‘/tmp‘)

[‘pulse-bGooj5bfoV3j‘, ‘keyring-TYL3NU‘, ‘.esd-0‘, ‘passwd‘, ‘keyring-e44AT1‘, ‘.ICE-unix‘, ‘orbit-gdm‘, ‘keyring-bQId2M‘, ‘keyring-oBIbPV‘, ‘pulse-OO5n4QneWCUz‘, ‘.X11-unix‘, ‘keyring-DiPD7a‘, ‘.X0-lock‘, ‘keyring-LyM6ui‘, ‘keyring-VpK6cb‘, ‘keyring-PE9XJn‘, ‘orbit-root‘]

>>> filelist = [f for f in os.listdir(‘/tmp‘)  if os.path.isfile(‘/tmp/‘ + f) ]

>>> filelist

[‘passwd‘, ‘.X0-lock‘]

 

用filter来判断isdir或isfile

>>> dirlist = filter( os.path.isfile,[ ‘/tmp/‘ + f for f in os.listdir(‘/tmp‘)] )

>>> dirlist

[‘/tmp/passwd‘, ‘/tmp/.X0-lock‘]

 

>>> os.chdir(‘/tmp‘)                              #切换到目录下

>>> dirlist = filter( os.path.isfile,os.listdir(‘./‘) )

>>> dirlist

[‘passwd‘, ‘.X0-lock‘]

>>> os.getcwd()

‘/tmp‘

 

 

变化角色的uid

其他用户做系统管理级的任务

import os,sys

print "Before: %d" % os.getuid()

os.seteuid(0)

print os.listdir(‘/root‘)

print "After: %d" % os.getuid()

 

给予权限,添加如下

[root@ht python]# vim /etc/sudoers

student ALL=NOPASSWD:/sbin/backup.py

 

 

>>> def jiecheng(n):

...     if n == 1:                                  #  不写的话:最大递归深度超过

...         return 1                            #不写:RuntimeError: maximum recursion depth exceeded

...     else:

...         return n * jiecheng(n-1)

...

>>> jiecheng(5)

120

 

join:绝对路径替换前面的相对的话相加

>>> nespath = os.path.join(os.getcwd(),‘/var/tmp‘)             #接两个路径参数

>>> nespath

‘/var/tmp‘

>>> nespath = os.path.join(os.getcwd(),‘tmp‘)

>>> nespath

‘/root/python/tmp‘

 

 

异常结构

- BaseException

|- KeyboardInterrupt

|- SystemExit

|- Exception

|- (all other current built-in exceptions)

 

 

assert:满足执行,不满足弹异常

#!/usr/bin/env python

 

a = int(raw_input("PLS input a number: "))

b = int(raw_input("PLS input b number: "))

 

assert a > b

 

print "=" * 50

pass

pass

如下所示:

[root@ht python]# python assert.py

PLS input a number: 12

PLS input b number: 1

==================================================

[root@ht python]# python assert.py

PLS input a number: 11

PLS input b number: 12

Traceback (most recent call last):

  File "assert.py", line 7, in <module>

    assert a > b

AssertionError

 

 

自定义弹出的错误

>>> def myError(res):

...     return IOError(res)

...

>>> m = myError("can‘t open file")

>>> raise m

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

IOError: can‘t open file

 

 

func(*tuple_grp_nonkw_args,**dict_grp_kw_args)

通过一个元组或字典作为参数组传递给函数时,其传入的参数的个数是任意的。

基本形式:

func(*tuple_grp_nonkw_args,**dict_grp_kw_args)

 

感觉有点像C语言中的指针变量,其中tuple_grp_nonkw_args是元组形式的非关键字参数组,而

dict_grp_kw_args则是装有关键字参数的字典。

 

使用:

def func(*tuple_args,**dict_args):

    print tuple_args

    print dict_args[‘name‘],dict_args[‘saving‘]

    pass

 

mytuple = (‘name‘,50.00)

mydict = {‘name‘:‘john‘,‘saving‘:50.00}

 

func(*mytuple,**mydict)

 

这种特性允许程序员在没有显示地对参数进行逐个声明的情况下调用函数,对参数较多或参数个数不定的函数非常有利。

 

课堂截图:

try..except嵌套使用

 

def创建的函数带参数

 

参数的顺序

 

求和函数示例

 

print_id和id的区别

 

12/5整理

__doc__的用法

>>> help(random.randint)         #等同于下面的利用__doc__

 

>>> random.randint.__doc__

‘Return random integer in range [a, b], including both end points.\n        ‘

>>> help(random.randint)

 

>>> print random.randint.__doc__

Return random integer in range [a, b], including both end points.

 

修饰符@和嵌套函数

代码如下

#!/usr/bin/env python

 

def outside(fuc):

    def in1():

        def in2():

            def in3():

 

                def in4():

                    fuc()

                print "called in4()"

                return in4

 

            print "called in3()"

            return in3

 

        print "called in2()"

        return in2

 

    print "called in1()"

    return in1

 

print "called outside()"

 

if __name__ == ‘__main__‘:

    @outside

    def foo():

        print "==END=="

 

    foo()()()()

运行代码如下

[root@ht python]# python inside.py

called outside()

called in1()

called in2()

called in3()

called in4()

==END==

 

map、apply、eval的运用

>>> map(lambda x,y : x + y,[10,11,12],[56,89,33])

[66, 100, 45]

>>> map (sum,[[10,21],[13,78]])

[31, 91]

>>> map(lambda x,y : x + y,[10,11,12])

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: <lambda>() takes exactly 2 arguments (1 given)

>>> map(lambda x,y : x + y,[10,11,12],[56,89,33])

[66, 100, 45]

>>> map(lambda x,y : x + y,[10,11,12],[56,89,33,78])

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

  File "<stdin>", line 1, in <lambda>

TypeError: unsupported operand type(s) for +: ‘NoneType‘ and ‘int‘

>>> map(lambda (x,y) : x + y,zip([10,11,12],[56,89,33,78]))

[66, 100, 45]

>>> apply(sum,[11,89])

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: ‘int‘ object is not iterable

>>> apply(sum,[[11,89]])

100

>>> apply(sum,[[11,89,200]])

300

>>> eval(‘sum([12,67])‘)

79

>>> eval(‘sum‘ + ‘(‘ + str([10,100]) + ‘)‘)

110

 

reduce求和的运用

>>> def mysum(x,y):

...     return x + y

...

>>> alist = [10,12,3,8]

>>> total = 0

>>> for i in alist:

...     total = mysum(total,i)

...

>>> print total

33

>>> b = reduce(lambda x,y:x + y,alist)

>>> b

33

 

 

filter的一行找出奇数

>>> b = filter(lambda x: x % 2,[random.randint(1,80) for i in range(10)])

>>> b

[9, 11, 43, 55, 43, 27, 73, 1, 13]

>>> b = filter(lambda x: x % 2,[random.randint(1,80) for i in range(10)])

>>> b

[13, 1, 51, 63]

 

 

map和zip的小区别

>>> map (None,[1,3,5],[2,8,9])

[(1, 2), (3, 8), (5, 9)]

>>> map (None,[1,3,5],[2,8,9,9])

[(1, 2), (3, 8), (5, 9), (None, 9)]

>>> zip([1,3,5],[2,6,8,1])

[(1, 2), (3, 6), (5, 8)]

 

lambda函数的局部变量

>>> y = 10

>>> bar = lambda : y * 10

>>> bar()

100

>>> y = 11

>>> bar()

110

>>> bar = lambda y = y : y * 10                 #y值的参数传入,成为局部的y

>>> bar()

110

>>> y = 12

>>> bar()

110

 

 

 

>>> def gen_rand():

...     while True:

...         yield random.randint(1,100)

...

>>> g = gen_rand()

>>> g.next()

21

>>> g.next()

2

课堂截图:

内嵌函数举例:

 

内嵌函数和修饰符写网页

 

 

 

 

全局变量和局部变量

 

lambda和作用域

 

 

 

12/6整理

模块导入路径

>>> import sys,os,math

>>> sys.path.append(‘/root/python‘)

>>> sys.path.insert(0,‘/root/python‘)

>>> print sys.path

[‘/root/python‘, ‘‘, ‘/usr/lib64/python26.zip‘, ‘/usr/lib64/python2.6‘, ‘/usr/lib64/python2.6/plat-linux2‘, ‘/usr/lib64/python2.6/lib-tk‘, ‘/usr/lib64/python2.6/lib-old‘, ‘/usr/lib64/python2.6/lib-dynload‘, ‘/usr/lib64/python2.6/site-packages‘, ‘/usr/lib64/python2.6/site-packages/gtk-2.0‘, ‘/usr/lib/python2.6/site-packages‘, ‘/usr/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg-info‘, ‘/root/python‘]

 

导入模块,只加载(reload)一次

>>> from mysort import my_cmp    #先导入mysort.pyc文件,所以可以在导入后删除.py文件

>>> dir()

[‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘my_cmp‘, ‘os‘, ‘sys‘]

>>> 

 

>>> from mysort import my_cmp as mc

>>> dir()

[‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘mc‘, ‘sys‘]

 

locals和globals返回局部或全局调用的字典

>>> locals()

{‘mc‘: <function my_cmp at 0x7ff30df6ec08>, ‘__builtins__‘: <module ‘__builtin__‘ (built-in)>, ‘__package__‘: None, ‘sys‘: <module ‘sys‘ (built-in)>, ‘__name__‘: ‘__main__‘, ‘__doc__‘: None}

>>> globals()

{‘mc‘: <function my_cmp at 0x7ff30df6ec08>, ‘__builtins__‘: <module ‘__builtin__‘ (built-in)>, ‘__package__‘: None, ‘sys‘: <module ‘sys‘ (built-in)>, ‘__name__‘: ‘__main__‘, ‘__doc__‘: None}

 

 

导入包目录时的操作

先生成包如下,

[root@ht tmp]# ls

[root@ht tmp]# mkdir Phone

[root@ht tmp]# cd Phone/

[root@ht Phone]# mkdir Voicedta

[root@ht Phone]# mkdir Fax

[root@ht Phone]# mkdir Mobile

[root@ht Phone]# mkdir Pager

[root@ht Phone]# touch __init__.py          #__init__.py必须有,可以为空,初始化模块

[root@ht Phone]# cd Fax/

[root@ht Fax]# touch __init__.py             

[root@ht Fax]# cd ../Mobile/

[root@ht Mobile]# touch __init__.py

 

>>> import sys

>>> sys.path.append(‘/tmp/‘)

>>> import Phone

>>> dir()

[‘Phone‘, ‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘sys‘]

>>> dir(Phone)

[‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘__path__‘]

>>> from Phone import Moblie

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

ImportError: cannot import name Moblie

>>> from Phone import *

>>> dir()

[‘Phone‘, ‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘sys‘]

打包之后的导入

[root@ht ~]# zip -r Phone.zip /tmp/Phone/

[root@ht ~]# cd python/

 

>>> import sys

>>> sys.path.append(‘~/Phone.zip‘)

>>> from Phone.Fax import *            #要存在该模块。Fax

 

也可将该模块包,解压包到/usr/lib64/python2.6/site-packages/下

                                               或者/usr/lib64/python2.6/dist-packages/下

 

也可修改linux下PYTHON的环境变量为模块所在目录

 

 

修改Phone目录下的__init__.py文件

#写入__all__ = [‘Fax’]              导入后可见

>>> dir()

[‘Phone‘, ‘__builtins__‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘, ‘sys‘]

>>> dir(Phone)

[‘Fax‘, ‘__all__‘, ‘__builtins__‘, ‘__doc__‘, ‘__file__‘, ‘__name__‘, ‘__package__‘, ‘__path__‘]

 

 

面向对象的编程

了解对象实例化:

>>> class MyClass():

...     pass

...

>>>

>>> ht = MyClass()

>>> type(MyClass),type(ht)

(<type ‘classobj‘>, <type ‘instance‘>)        

 

>>> import pprint

>>> pprint.pprint(ht)

<__main__.MyClass instance at 0x7f65a972f758>

>>> print(ht)

<__main__.MyClass instance at 0x7f65a972f758>

 

#!/usr/bin/env python

class Student():

    name = ‘unknown‘

    age = 0

    def promo(self):

        print "%s are %d years old." % (self.name,self.age)

 

ht = Student()                      #实例化对象

ht.name = ‘huangteng‘       #对象自己修改属性值

ht.age = 22

 

Student.promo(ht)             #类调用方法给对象

ht.promo()                           #对象直接调用方法

 

print "=" * 50

 

lz = Student()                      #示例化的对象

lz.promo()                                     #调用默认属性值

 

指向代码如下:

[root@ht python]# python class.py

huangteng are 22 years old.

huangteng are 22 years old.

==================================================

unknown are 0 years old.

 

 

lib 库

函数原型:find(str, pos_start, pos_end)

解释:

str:被查找“字串”

pos_start:查找的首字母位置(从0开始计数。默认:0)

pos_end: 查找的末尾位置(默认-1)

返回值:如果查到:返回查找的第一个出现的位置。否则,返回-1。

 

threading

>>> import shlex

>>>

>>> command = ‘df -h‘               #可以接多个shell命令,用于Python的subprocess

>>> cmdlist = shlex.spilt(command)

 

 

 

>>> import subprocess

 

>>> p = subprocess.Popen(‘df -h‘,shell = True,stdout = True)

>>> Filesystem            Size  Used Avail Use% Mounted on

/dev/mapper/myvol-root

                       12G  3.8G  7.4G  34% /

tmpfs                 491M   72K  491M   1% /dev/shm

/dev/sda1             190M   28M  153M  16% /boot

/dev/mapper/myvol-home

                      488M  464K

 

 

>>> p = subprocess.Popen(‘df -h;cat /tmp/haha‘,shell = True,stdout = subprocess.PIPE)

>>> cat: /tmp/haha: No such file or directory

>>> s,e = p.communicate()

 

 

>>> p = subprocess.Popen(‘df -h; cat /tmp/haha‘,shell = True,stdout = subprocess.PIPE,stderr = subprocess.PIPE

>>> s,e = p.communicate()

>>> s

‘Filesystem            Size  Used Avail Use% Mounted on\n/dev/mapper/myvol-root\n                    491M   72K  491M   1% /dev/shm\n/dev/sda1             190M   28M  153M  16% /boot\n/dev/mapper/my  1% /home\n‘

>>> e

‘cat: /tmp/haha: No such file or directory\n‘

 

re

>>> import re

>>>

>>> re.findall(‘\Aabc‘,‘abcdefg‘)

[‘abc‘]

>>> re.findall(‘fg\Z‘,‘abcdefg‘)

[‘fg‘]

>>> re.findall(‘\w‘,‘abcd123%$#_@!&*^./‘)

[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘1‘, ‘2‘, ‘3‘, ‘_‘]

>>> re.findall(‘\W‘,‘abcd123%$#_@!&*^./‘)

[‘%‘, ‘$‘, ‘#‘, ‘@‘, ‘!‘, ‘&‘, ‘*‘, ‘^‘, ‘.‘, ‘/‘]

>>> a = ‘this a demo.‘

>>> re.findall(‘\b‘,a)                             

[]

>>> re.findall(‘\B‘,a)                            

[‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘, ‘‘]

>>> re.findall(‘\s‘,a)                             

[‘ ‘, ‘ ‘]

>>> re.findall(‘\S‘,a)                             

[‘t‘, ‘h‘, ‘i‘, ‘s‘, ‘a‘, ‘d‘, ‘e‘, ‘m‘, ‘o‘, ‘.‘]

>>> re.findall(‘[^\s]‘,a)                         

[‘t‘, ‘h‘, ‘i‘, ‘s‘, ‘a‘, ‘d‘, ‘e‘, ‘m‘, ‘o‘, ‘.‘]

>>> re.findall(‘[^\b]‘,a)                        

[‘t‘, ‘h‘, ‘i‘, ‘s‘, ‘ ‘, ‘a‘, ‘ ‘, ‘d‘, ‘e‘, ‘m‘, ‘o‘, ‘.‘]               

 

glob

>>> print glob.glob(‘/tmp/*/‘)

[‘/tmp/pulse-HX0yia9NX8uw/‘, ‘/tmp/orbit-gdm/‘, ‘/tmp/pulse-lLqkS6JBZwTm/‘, ‘/tmp/Phone/‘, ‘/tmp/keyring-c2Qlfi/‘, ‘/tmp/orbit-root/‘]

>>> print glob.glob(‘/tmp/?/‘)

[]

>>> print glob.glob(‘/tmp/?????/‘)

[‘/tmp/Phone/‘]

>>> print glob.glob(‘/tmp/[a-z]*/‘)

[‘/tmp/pulse-HX0yia9NX8uw/‘, ‘/tmp/orbit-gdm/‘, ‘/tmp/pulse-lLqkS6JBZwTm/‘, ‘/tmp/keyring-c2Qlfi/‘, ‘/tmp/orbit-root/‘]

>>> print glob.glob(‘/tmp/*[0-9]*/‘)

[‘/tmp/pulse-HX0yia9NX8uw/‘, ‘/tmp/pulse-lLqkS6JBZwTm/‘, ‘/tmp/keyring-c2Qlfi/‘]

 

python学习笔记