##################### 1. list 的复制 #####################
L = range(10)
L1 = L #L1为L的别名,用C来说就是指针地址相同,对L1操作即对L操作。函数参数就是这样传递的
L1 = L[:] #L1为L的克隆,即另一个拷贝。
L.pop()
#L = L1 = [0,1,2,3,4,5,6,7,8]
#L2 = range(10)
##################### 2.可变参数与关键字参数 #####################
- def foo(arg1,arg2,*nkw,**kw): # * -->tuple ** -->dict
- print 'arg1 is: ', arg1
- print 'arg2 is: ', arg2
- for eachNKW in nkw: print 'arg: ', eachNKW
- for eachKW in kw.keys(): print "key arg '%s': '%s'" %(eachKW,kw[eachKW])
- #for example
- a_tuple=('x','y','z')
- a_dict={'A':10,'B':20}
- foo(1,2,3,4,5,lang='Python',ver=2.7,*a_tuple,**a_dict)
关键字参数:
- def foo(x):
- print x
- foo(23);foo('chain') #标准调用
- foo(x=23);foo(x='chain') #关键字调用
##################### 3.列表生成式 #####################
某次一公司面试问过什么是刘表生成式, 只知道用,不知道名。
列表表达式,是列表解析的一种扩展。
列表解析:[expr for iter_var in iterable if cond_expr]
列表表达式:(expr for iter_var in iterable if cond_expr)
使用列表表达式可以避免创建列表,它并不真正创建列表,而是返回一个生成器。这个生成器在每次计算出一个条目后,把这个条目yield出来。 生成器表达式使用了azy evaluation,只有在检索时才被赋值,所以在列表比较长的情况下使用内存上更有效。这样可以更节省内存,提高执行效率。
##################### 4.[python]创建简单线程的两种方法 #####################
来源: http://www.yabogo.com/?p=596
import threading
#方法一
def sayHello (name ):
print "Hello,I'm Thread-%s"% (name )
for i in range ( 4 ):
t = threading. Thread (target =sayHello ,args = (i+ 1 , ) )
t. start ( ) #启动线程
#方法二
class ThreadClass ( threading. Thread ):
def run ( self ):
er = self. getName ( ) #自动获取当前线程名
print "Hello,I'm %s"%er
for i in range ( 4 ):
t = ThreadClass ( )
t. start ( )
##################### 4.socket_family 作用初解 #####################
tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定端口 IP
tcpCosk = socket.socket(socket.AF_UNIX, socket.SOCKET_STREAM) # 绑定文件 类型s pipe 通信
class Socket():
def __init__ (self):
self.connection = ''
self.address = ''
self.connlist = []
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if os.path.exists('/tmp/pipe.d'):
os.unlink('/tmp/pipe.d')
self.sock.bind('/tmp/pipe.d')
retcode,proc = utils.cust_popen('/bin/chmod 777 /tmp/pipe.d')
if retcode != 0:
print >> sys.stderr,proc.stderr.readlines()
def Listen (self):
try:
self.sock.listen(100)
if self.connlist != []:
infds,outfds,errfds = select.select([self.sock,],[],[],0)
if len(infds) != 0:
self.connection,self.address = self.sock.accept()
self.connlist.append(self.connection)
else:
self.connection,self.address = self.sock.accept()
self.connlist.append(self.connection)
except:
setting.errlogdata(setting.LINE(),'socketclass.py','listen error')
def Senddata (self,conn,senddata = 'ok'):
try:
sendbuf = conn.send(senddata)
except:
setting.errlogdata(setting.LINE(),'socketclass.py','send data error')
def Recvdata (self,conn,queue):
conn.setblocking(0)
try:
readbuf = conn.recv(512)
if readbuf == '':
return 2
else:
data = json.loads(readbuf)
if data['op'] != 'raidlist':
queue.put(data)
readbuf = ''
return 0
else:
return 3
except:
return 1
def CloseConn (self,conn):
try:
self.connlist.remove(conn)
conn.close()
except:
setting.errlogdata(setting.LINE(),'socketclass.py','close connect error')
##################### 5.文件操作 #####################
rootdir = " d:/download "
for parent, dirnames, filenames in os.walk(rootdir):
# case 1:
for dirname in dirnames:
print ( " parent is: " + parent)
print ( " dirname is: " + dirname)
# case 2
for filename in filenames:
print ( " parent is: " + parent)
print ( " filename with full path : " + os.path.join(parent, filename))
''' 知识点:
* os.walk返回一个三元组.其中dirnames是所有文件夹名字(不包含路径),filenames是所有文件的名字(不包含路径).parent表示父目录.
* case1 演示了如何遍历所有目录.
* case2 演示了如何遍历所有文件.
* os.path.join(dirname,filename) : 将形如"/a/b/c"和"d.java"变成/a/b/c/d.java".
'''
分割路径和文件名
# 常用函数有三种:分隔路径,找出文件名.找出盘符(windows系统),找出文件的扩展名.
# 根据你机器的实际情况修改下面参数.
spath = " D:/download/repository.7z "
# case 1:
p,f = os.path.split(spath);
# case 2:
drv,left = os.path.splitdrive(spath);
# case 3:
f,ext = os.path.splitext(spath);
'''
知识点: 这三个函数都返回二元组.
* case1 分隔目录和文件名
* case2 分隔盘符和文件名
* case3 分隔文件和扩展名
'''
vec_add = lambda a,b : tuple([x+y for x,y in zip(a,b)])
[vec_add(a,b) for a,b in zip(list1, list2)]
l1 = [ [0, 0, 0], [1, 1, 1] ]
l2 = [ [2, 2, 2], [3, 3, 3] ]
>>> [x+y for x,y in zip(l1,l2)]
[[0, 0, 0, 2, 2, 2], [1, 1, 1, 3, 3, 3]]
>>> vec_add = lambda a,b : tuple([x+y for x,y in zip(a,b)])
>>> [vec_add(a,b) for a,b in zip(l1, l2)]
[(2, 2, 2), (4, 4, 4)] # 没处理成 【【】,【】】 格式 [ [ ], [ ] ]
>>> lll = [vec_add(a,b) for a,b in zip(l1, l2)]
>>> [list(i) for i in lll]
[[2, 2, 2], [4, 4, 4]]
##################### 6. 创建二维数组 #####################
def genMatrix(rows,cols):
matrix = [[0 for col in range(cols)] for row in range(rows)]
for i in range(rows):
for j in range(cols):
x = random.randint(1,9)
matrix[i][j] = x
return matrix