码迷,mamicode.com
首页 > 编程语言 > 详细

python学习笔记

时间:2016-02-01 21:01:18      阅读:401      评论:0      收藏:0      [点我收藏+]

标签:

一、冒泡算法实例:

a = [32,5,22,41,7,31,12,102,74,37,9,25]

   1、方法1:


 

for i in range(len(a)):
for j in range(len(a)-1):
if a[j] > a [j+1]:
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp

print(a)
注:此方法会循环12*11次,会进行多次不必要的判断

2、方法2:

for i in range(len(a)):
for j in range(len(a)-i):
if a[j] > a [j+1]:
tmp = a[j]
a[j] = a[j+1]
a[j+1] = tmp

print(a)
注:此方法即正常循环

一、常用函数说明:

 ★ lamba

python lambda是在python中使用lambda来创建匿名函数,而用def创建的方法是有名称的,除了从表面上的方法名不一样外,python lambda还有哪些和def不一样呢?

1 python lambda会创建一个函数对象,但不会把这个函数对象赋给一个标识符,而def则会把函数对象赋值给一个变量。
2 python lambda它只是一个表达式,而def则是一个语句。

 

lambda语句中,冒号前是参数,可以有多个,用逗号隔开,冒号右边的返回值。lambda语句构建的其实是一个函数对象。

例:

m = lambda x,y,z: (x-y)*z
print m(234,122,5)

 

也经常用于生成列表,例:


list = [i ** i for i in range(10)]
print(list)

list_lambda = map(lambda x:x**x,range(10))
print(list_lambda)


 

 ★ enumerate(iterable,[start])   iterable为一个可迭代的对象;

enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object.  iterable must be another object  that supports iteration.  The enumerate object yields pairs containing a count  (from start, which defaults to zero) and a value yielded by the iterable 
 argument. enumerate is useful for obtaining an indexed list:    (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

例:


for k,v in enumerate([‘a‘,‘b‘,‘c‘,1,2,3],10):
        print k,v 


 

★S.format(*args, **kwargs) -> string  字符串的格式输出,类似于格式化输出%s

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces (‘{‘ and ‘}‘).

s = ‘i am {0},{1}‘
print(s.format(‘wang‘,1))

 

★map(function,sequence) 将squence每一项做为参数传给函数,并返回值

例:


def add(arg):
    return arg + 101
print(map(add,[12,23,34,56]))


 

★filter(function or None, sequence) -> list, tuple, or string  返还true的序列
        Return those items of sequence for which function(item) is true.  If
    function is None, return the items that are true.  If sequence is a tuple
    or string, return the same type, else return a list.

例:


def comp(arg):
    if arg < 8:
        return True
    else:
        return False  
print(filter(comp,[1,19,21,8,5]))
print(filter(lambda x:x % 2,[1,19,20,8,5]))
print(filter(lambda x:x % 2,(1,19,20,8,5)))
print(filter(lambda x:x > ‘a‘,‘AbcdE‘))


 

★reduce(function, sequence[, initial]) -> value   对二个参数进行计算
Apply a function of two arguments cumulatively to the items of a  sequence,
from left to right, so as to reduce the sequence to a single value.For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5).  If initial is present, it is placed before the 
 items of the sequence in the calculation, and serves as a default when  the sequence is empty.

例:


print(reduce(lambda x,y:x*y,[22,11,8]))
print(reduce(lambda x,y:x*y,[3],10))

print(reduce(lambda x,y:x*y,[],5))


 

★zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] 将多个序列转化为新元祖的序列
Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences.  The returned list is  truncated in length to the length of the shortest argument sequence.

例:


a = [1,2,3,4,5,6]
b = [11,22,33,44,55]
c = [111,222,333,444]
print(zip(a,b,c))


 

★eval(source[, globals[, locals]]) -> value 将表达式字符串执行为值,其中globals为全局命名空间,locals为局部命名空间,从指字的命名空间中执行表达式,
        Evaluate the source in the context of globals and locals.    The source may be a string representing a Python expression  or a code object as returned by compile().    The globals must be a dictionary and locals can be any mapping,    defaulting to the current globals and locals.    If only globals is given, locals defaults to it.

例:


a = ‘8*(8+20-5%12*23‘
print(eval(a))

d = {‘a‘:5,‘b‘:4}
print(eval(‘a*b‘,d))


 

★exec(source[, globals[, locals]]) 语句用来执行储存在字符串或文件中的Python语句

例:


a = ‘print("nihao")‘

b = ‘for i in range(10): print i‘

exec(a) 

exec(b)


 

★execfile(filename[, globals[, locals]])
     Read and execute a Python script from a file.The globals and locals are dictionaries, defaulting to the currentglobals and locals.  If only globals is given, locals defaults to it.

 

二、模块 paramiko

paramiko是一个用于做远程控制的模块,使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,fabric和ansible内部的远程管理就是使用的paramiko来现实。

1、下载安装(pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto)

2、使用模块

技术分享 通过用户名和密码连接服务器
技术分享 过密钥链接服务器
技术分享 上传或者下载文件 - 通过用户名和密码
技术分享 上传或下载文件 - 通过密钥

 

三、其他常用模块:

1、random模块:

★random 生成随机数

print random.random()             生成0-1之间的小数

print random.randint(1,3)         生成整数,包含endpoint

print random.randrange(1,3,2)    生成整数,不包含endpoint

randrange(self, start, stop=None, step=?)

生成5位随机数,例:


import random

a = []
for i in range(5):
    if i == random.randint(1,5):
        a.append(str(i))
    else:
        a.append(chr(random.randint(65,90)))
else:        
    print(‘‘.join(a))

 

2、MD5、sha、hashlib模块

★生成MD5码

例:


一. 使用md5包

import md5
src = ‘this is a md5 test.‘   
m1 = md5.new()   
m1.update(src)   
print m1.hexdigest()

二、使用sha包

import sha

hash = sha.new()

hash.update(‘admin‘)

print hash.hexdigest()

三. 使用hashlib

用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

import hashlib
hash = hashlib.md5()
hash.update(‘this is a md5 test.‘)

hash.update(‘admin‘)

print(hash.digest())

print(hash.hexdigest())

技术分享 hashlib

推荐使用第三种方法。

 

对以上代码的说明:

1.首先从python直接导入hashlib模块

2.调用hashlib里的md5()生成一个md5 hash对象

3.生成hash对象后,就可以用update方法对字符串进行md5加密的更新处理

4.继续调用update方法会在前面加密的基础上更新加密

5.加密后的二进制结果

6.十六进制结果

如果只需对一条字符串进行加密处理,也可以用一条语句的方式:

print(hashlib.new("md5", "Nobody inspects the spammish repetition").hexdigest())


 

以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密

1
2
3
4
5
6
7
import hashlib
 
# ######## md5 ########
 
hash = hashlib.md5(‘898oaFs09f‘)
hash.update(‘admin‘)
print hash.hexdigest()

还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密

1
2
3
4
import hmac
= hmac.new(‘wueiqi‘)
h.update(‘hellowo‘)
print h.hexdigest()

不能再牛逼了!!!

 

3、pickle和json模块:

python对象与文件之间的序列化和反序列化(pickle和json)

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

 

pickle模块用来实现python对象的序列化和反序列化。通常地pickle将python对象序列化为二进制流或文件。

 python对象与文件之间的序列化和反序列化:

pickle.dump()

pickle.load()

如果要实现python对象和字符串间的序列化和反序列化,则使用:

pickle.dumps()

pickle.loads()

 

 

可以被序列化的类型有:

* None,True 和 False;

* 整数,浮点数,复数;

* 字符串,字节流,字节数组;

* 包含可pickle对象的tuples,lists,sets和dictionaries;

* 定义在module顶层的函数:

* 定义在module顶层的内置函数;

* 定义在module顶层的类;

* 拥有__dict__()或__setstate__()的自定义类型;

注意:对于函数或类的序列化是以名字来识别的,所以需要import相应的module。

例:


import pickle

data = {
    ‘a‘: [1, 2.0, 3, 4+6j],
    ‘b‘: ("character string", "byte string"),
    ‘c‘: set([None, True, False])
}
du = pickle.dumps(data)
print(pickle.loads(du))
print(du)

with open(‘data.pickle‘, ‘wb‘) as f:
      pickle.dump(data, f)

with open(‘data.pickle‘, ‘rb‘) as f:
    data = pickle.load(f)
    print(str(data))


 

★JSON(JavaScript Object Notation):一种轻量级数据交换格式,相对于XML而言更简单,也易于阅读和编写,机器也方便解析和生成,Json是JavaScript中的一个子集。

        Python的Json模块序列化与反序列化的过程分别是 encoding和 decoding

encoding:把一个Python对象编码转换成Json字符串
decoding:把Json格式字符串解码转换成Python对象

具体的转化对照如下:

技术分享

 

loads方法返回了原始的对象,但是仍然发生了一些数据类型的转化。比如,上例中‘abc’转化为了unicode类型。从json到python的类型转化对照如下:

 

技术分享

例:


import json
data = {    ‘a‘: [1, 2.0, 3, 4],    ‘b‘: ("character string", "byte string"),    ‘c‘: ‘abc‘}

du = json.dumps(data)
print(du)
print(json.loads(du,encoding=‘ASCII‘))

 

with open(‘data.json‘,‘wb‘) as f:
    json.dump(data,f)

 

with open(‘data.json‘,‘rb‘) as f:
    data = json.load(f)
    print(repr(data))


经测试,2.7版本导出的json文件,3.4版本导入会报错:TypeError: the JSON object must be str, not ‘bytes‘

 

4、正则表达式模块:

re模块用于对python的正则表达式的操作。

字符:

  . 匹配除换行符以外的任意字符
  \w 匹配字母或数字或下划线或汉字
  \s 匹配任意的空白符
  \d 匹配数字
  \b 匹配单词的开始或结束
  ^ 匹配字符串的开始
  $ 匹配字符串的结束

次数:

  * 重复零次或更多次
  + 重复一次或更多次
  ? 重复零次或一次
  {n} 重复n次
  {n,} 重复n次或更多次
  {n,m} 重复n到m次

IP:
^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$
手机号:
^1[3|4|5|8][0-9]\d{8}$

★re.match的函数原型为:re.match(pattern, string, flags)

第一个参数是正则表达式,这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None;

第二个参数表示要匹配的字符串;

第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

 

★re.search的函数原型为: re.search(pattern, string, flags)

每个参数的含意与re.match一样。 

re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

 

★re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r‘\w*oo\w*‘, text);获取字符串中,包含‘oo‘的所有单词。

 

★re.sub的函数原型为:re.sub(pattern, repl, string, count)

其中第二个函数是替换后的字符串;本例中为‘-‘

第四个参数指替换个数。默认为0,表示每个匹配项都替换。

re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r‘\s‘, lambda m: ‘[‘ + m.group(0) + ‘]‘, text, 0);将字符串中的空格‘ ‘替换为‘[ ]‘。

 

★re.split可以使用re.split来分割字符串,如:re.split(r‘\s+‘, text);将字符串按空格分割成一个单词列表。

根据指定匹配进行分组

content = "‘1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )‘"
new_content = re.split(‘\*‘, content)
# new_content = re.split(‘\*‘, content, 1)
print new_content
content = "‘1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )‘"
new_content = re.split(‘[\+\-\*\/]+‘, content)
# new_content = re.split(‘\*‘, content, 1)
print new_content
inpp = ‘1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))‘
inpp = re.sub(‘\s*‘,‘‘,inpp)
new_content = re.split(‘\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)‘, inpp, 1)
print new_content

★re.compile可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。下面是一个正则表达式对象的一个例子:

例:


import re

r = re.compile(‘\d+‘)
r1 = r.match(‘adfaf123asdf1asf1123aa‘)
if r1:
    print(r1.group())
else:
    print(‘no match‘)

r2 = r.search(‘adfaf123asdf1asf1123aa‘)
if r2:
    print(r2.group())
    print(r2.groups())
else:
    print(‘no match‘)
    
r3 = r.findall(‘adfaf123asdf1asf1123aa‘)
if r3:
    print(r3)
else:
    print(‘no match‘)
    
r4 = r.sub(‘###‘,‘adfaf123asdf1asf1123aa‘)
print(r4)

r5 = r.subn(‘###‘,‘adfaf123asdf1asf1123aa‘)
print(r5)

r6 = r.split(‘adfaf123asdf1asf1123aa‘,maxsplit=2)
print(r6)


注:re执行分二步:首先编译,然后执行。故先使用re.compile进行查询的字符串进行编译,之后的操作无需在次编译,可以提高效率。

匹配IP具体实例:

 


ip = ‘12aa13.12.15aasdfa12.32aasdf192.168.12.13asdfafasf12abadaf12.13‘
res = re.findall(‘(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})‘,ip)
print(res)
res1 = re.findall(‘(?:\d{1,3}\.){3}\d{1,3}‘,ip)
print(res1)


 

     而group,groups 主要是针对查询的字符串是否分组,一般只是针对search和match,即‘\d+‘ 和(‘\d+‘) 输出结果为:

123   和(‘123‘,)。

技术分享
import re
a = ‘Oldboy School,Beijing Changping shahe:010-8343245‘

match = re.search(r‘(\D+),(\D+):(\S+)‘,a)
print(match.group(1))
print(match.group(2))
print(match.group(3))

print("##########################")

match2 = re.search(r‘(?P<name>\D+),(?P<address>\D+):(?P<phone>\S+)‘,a)
print(match2.group(‘name‘))
print(match2.group(‘address‘))
print(match2.group(‘phone‘))
技术分享

 

 

5、time模块

time模块提供各种操作时间的函数
import time
#1、时间戳    1970年1月1日之后的秒
#3、元组 包含了:年、日、星期等... time.struct_time
#4、格式化的字符串    2014-11-11 11:11

技术分享

 
print time.time()
print time.mktime(time.localtime())
 
print time.gmtime()    #可加时间戳参数
print time.localtime() #可加时间戳参数
print time.strptime(‘2014-11-11‘, ‘%Y-%m-%d‘)
 
print time.strftime(‘%Y-%m-%d‘) #默认当前时间
print time.strftime(‘%Y-%m-%d‘,time.localtime()) #默认当前时间
print time.asctime()
print time.asctime(time.localtime())
print time.ctime(time.time())
 
import datetime
‘‘‘
datetime.date:表示日期的类。常用的属性有year, month, day
datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
datetime.datetime:表示日期时间
datetime.timedelta:表示时间间隔,即两个时间点之间的长度
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
strftime("%Y-%m-%d")
‘‘‘
import datetime
print datetime.datetime.now()
print datetime.datetime.now() - datetime.timedelta(days=5)

 

6、shutil模块

高级的 文件、文件夹、压缩包 处理模块

shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中,可以部分内容

shutil.copyfile(src, dst) 拷贝文件

shutil.copymode(src, dst)

仅拷贝权限。内容、组、用户均不变

shutil.copystat(src, dst)

拷贝状态的信息,包括:mode bits, atime, mtime, flags

shutil.copy(src, dst)

拷贝文件和权限

shutil.copy2(src, dst)

拷贝文件和状态信息

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件

例如:copytree(source, destination, ignore=ignore_patterns(‘*.pyc‘, ‘tmp*‘))

shutil.rmtree(path[, ignore_errors[, onerror]])

递归的去删除文件

shutil.move(src, dst)
递归的去移动文件

shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

  • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如:www                        =>保存至当前路径
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
  • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
  • root_dir: 要压缩的文件夹路径(默认当前目录)
  • owner: 用户,默认当前用户
  • group: 组,默认当前组
  • logger: 用于记录日志,通常是logging.Logger对象
1
2
3
4
5
6
7
8
9
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
 
import shutil
ret = shutil.make_archive("wwwwwwwwww"‘gztar‘, root_dir=‘/Users/wupeiqi/Downloads/test‘)
 
 
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww"‘gztar‘, root_dir=‘/Users/wupeiqi/Downloads/test‘)

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,

 

7、ConfigParser

用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

1.基本的读取配置文件

-read(filename) 直接读取ini文件内容

-sections() 得到所有的section,并以列表的形式返回

-options(section) 得到该section的所有option

-items(section) 得到该section的所有键值对

-get(section,option) 得到section中option的值,返回为string类型

-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

 

2.基本的写入配置文件

-add_section(section) 添加一个新的section

-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

 

3.Python的ConfigParser Module中定义了3个类对INI文件进行操作。

分别是RawConfigParser、ConfigParser、 SafeConfigParser。

RawCnfigParser是最基础的INI文件读取类;

ConfigParser、 SafeConfigParser支持对%(value)s变量的解析。 

 

设定配置文件test.conf


[portal] 

url = http://%(host)s:%(port)s/Portal 

host = localhost 

port = 8080 


使用RawConfigParser:

 


import ConfigParser 

file1 = ConfigParser.RawConfigParser()

file1.read(‘aa.txt‘)

print(file1.get(‘portal‘,‘url‘))

得到终端输出:

http://%(host)s:%(port)s/Portal


 

使用ConfigParser:


import ConfigParser 

file2 = ConfigParser.ConfigParser()

file2.read(‘aa.txt‘)
print(file2.get(‘portal‘,‘url‘))

得到终端输出:

http://localhost:8080/Portal


 

使用SafeConfigParser:


import ConfigParser 

 

cf = ConfigParser.SafeConfigParser() 

file3 = ConfigParser.SafeConfigParser()

file3.read(‘aa.txt‘)
print(file3.get(‘portal‘,‘url‘))

得到终端输出(效果同ConfigParser):

http://localhost:8080/Portal

 

举例说明:

技术分享 configparser

 

8、logging模块:

 

用于便捷记录日志且线程安全的模块

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import logging
 
 
logging.basicConfig(filename=‘log.log‘,
                    format=‘%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s‘,
                    datefmt=‘%Y-%m-%d %H:%M:%S %p‘,
                    level=10)
 
logging.debug(‘debug‘)
logging.info(‘info‘)
logging.warning(‘warning‘)
logging.error(‘error‘)
logging.critical(‘critical‘)
logging.log(10,‘log‘)

 

对于等级:

 

1
2
3
4
5
6
7
8
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

 

只有大于当前日志等级的操作才会被记录。

 

对于格式,有如下属性可是配置:

 

技术分享



python学习笔记

标签:

原文地址:http://www.cnblogs.com/xiaodi914/p/5176125.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!