首页 > 学院 > 开发设计 > 正文

没准在笔试里可以用的到(持续更新中)

2019-11-14 17:40:54
字体:
来源:转载
供稿:网友

1.计算阶乘

  通常你是这样写: 

def func(n):	return n<2 and 1 or n*func(n-1)
reduce (lambda x,y:x*y,range(1,n))    #简单多了?高大上了?

  

2.写(读)文件:

f=open(name,'w')f.write(data)f.close()

也可以这样:

with open(name,'w') as f:    f.write(data)    #不用关闭文件!

3.python 的私有:

  想私有方法或者私有变量:方法或变量名前加'__': def __myfunc()    __color = ''

  "单下划线" 开始的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量;
  "双下划线" 开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。

4.遍历目录:

import os.pathdef Vist(arg,dirname,names):    for filepath in names:      PRint os.path.join(dirname,filepath) path ='xxxx' 目录路径os.path.walk(path,Vist,())  #Vist 回调函数  先遍历顶级目录,在遍历目录中文件

5.1,2,3,4,5的全排列

from itertools import permutations p = list(permutations('12345'))

当然也可以用递归,或者好多好多个for

递归:

def perms(elements):    if len(elements) <=1:        yield elements    else:        for perm in perms(elements[1:]):            for i in range(len(elements)):                yield perm[:i] + elements[0:1] + perm[i:]for item in list(perms([1,2,3,4,5])):    print item

6.获取上一级目录

import os,os.pathpath = os.getcwd()parent_path = os.path.dirname(path)print pathprint parent_path

7.combinations(iterable, r),创建一个迭代器,返回iterable中所有长度为r的子序列(不重复)

from itertools import *for i in combinations([1, 2,3,4], 2):    print i

8.功能同上,重复

from itertools import *for i in combinations_with_replacement([1, 2, 3,4], 2):    print i

9.删除列表中相同的字典

from itertools import *l = [{'name':'zhang', 'age':18}, {'name':'zhang', 'age':18}, {'name':'li', 'age':18}]for d1, d2 in combinations(l, 2):    a = list(set(d1.items())^set(d2.items()))    if len(a) == 0:        i = l.index(d1)        l.pop(i)print l

10.同时遍历两个数组(字典),[过去写爬虫(beautifulSoup)的时候遇到过,同时遍历两类元素的]

b = [1,2,3]a = [4,5,6,7]for i, j in zip(a, b):	print i, j

11.当你有两个列表,其中一个为空,如果想使用其中一个不空列表的时候

b = [1,2,3]a = []for i in set(a) | set(b):	print i

12.直接插入到列表某位置:

a=[1,2,3]a.insert(3,1111)print a

  

 

 

  

 

  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表