.log#!/usr/bin/python27
# -*- coding:utf-8 -*-
filelist1=os.listdir('/var/log')
example1:
s1='hello.log'
>>>s1.endswith('.log')
>>> True
example2:查出filelist1中所有以log结尾的文件
filelist2=[i for i in filelist1 if i.endswith('.log')]
print filelist2
列表解析:根据已有列表,生成新列表方式:
l1=['x','y','z']
l2=[1,2,3]
l3=[(i,j) for i in l1 for j in l2]
print l3
[('x',1),('x',2).....]
OR
l1=['x','y','z']
l2=[1,2,3]
l3=[(i,j) for i in l1 for j in l2 if j!=1]
print l3
生成器表达式:
生成器表达式并不会真正创建数字列表,而是返回一个生成器对象,此对象每次计算出一条目录后,把这条目‘产生’(yield‘)出来
语法:
(expr for iter_var in iterabl)
(expr for iter_var in iterabl if cond_expr)
例子:
[i**2 for i in range(1,11)]
g1=(i**2 for i in range(1,11))
g1.next()
1
g1.next()
4
.
.
.
产生偏移和元素:
enumerate
range可在非完备遍历中生成索引偏移。
如果同时需要索引和·偏移元素,可以使用enumerate
内置函数返回一个生成器对象
S=’HELLO WORD‘
E=enumerate(S)
E.next()
(0,'H')
E.next()
(0,'E')
文件系统OS和文件:
1、文件是计算机中由os管理具有名字和存储区域
2、在linux系统上,文件被看作字节序列
文件-----01010101010(文件流)-----进程
python打开文件:
python内置函数open()用于打开文件和创建文件(open(name[,model[,bufsize]])
open方法可以接受三个参数:文件名、模式、和缓冲区参数
open函数返回一个文件对象
mode:指定文件打开模式
bufsize:定义输出缓存
:0表示无缓存
1表示由缓存
负数表示使用系统默认设置
正数表示使用近似指定大小缓冲
文件打开模式:
r :只读
open('/var/log/message.log','r')
w:写入
a;附加
只在模式后用’+‘表示同意输入输出r+,w+,a+
在模式后附加’b'表示以二进制打开文件
rb,wb+
.log#!/usr/bin/python27
# -*- coding:utf-8 -*-
import os
import os.path
filename='/tep/test.txt'
if os.path.isfile(filename):
f=open(filename,'a+')
while True:
line=raw_input('Enter something>')
if line=='q' or line=='quit':
break;
f.write(line+'
')
f1.close();
函数:是为了代码最大程度的重用和最小化代码的冗余提供的基本程序结构
pyhton:4种函数
全局
局部
方法
lambad:表达式
创建函数:
语法:
def functionName(parameters):
suite
return True
函数定义里本地作用域,模块定义了全局作用域
lambed函数
f20=lambda x,y:x+y
>>>f20(3,4)
>>> 7
def f20(x,y):
return x+y
函数式编程
可以称作泛函编程,是一种编程范型
他将电脑运算视为数学上的函数计算,并避免状态以及可编数据。
filter过滤器:filter()
def startPOs(m,n):
def newPos(x,y):
print "the old position is (%d,%d),and the new position is (%d,%d) "%(m,n,m+x,n+y)
return newPos
>>>action=startPos(10,10)
>>>action(1,2)
>>> the old position is (10,10),and the new position is (11,12)
>>> action(-1,3)
>>> the old position is (10,10),and the new position is (9,13)
例子:
for i in (j**2 for j in range(1,11)):
print i
例子:
def deco(func):
def wrapper():
print "place say somthing"
func()
print "no zou no die....."
return wrapper
@deco
def show():
return "i am from Mars."
show()
place say somthing
no zou no die....
面向对象(oop):{封装、继承、多态}
面向过程:
程序=指令+数据
代码可以选择以指令为核心或以数据为核心进行编写
以指令为核心:围绕正在发生什么“进行编写”
类关系
'递归函数实际应用案例,二分查找'
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
def binary_search(dataset,find_num):
print(dataset)
if len(dataset) >1:
mid = int(len(dataset)/2)
if dataset[mid] == find_num: #find it
print("找到数字",dataset[mid])
elif dataset[mid] > find_num :# 找的数在mid左面
print("