- Python基础
- 文件操作
- 模块与包
- 数据类型
- 企业面试题
- 15.python新式类和经典类的区别?
- 16.python中内置的数据结构有几种?
- 17.python如何实现单例模式?请写出两种实现方式?
- 18.反转一个整数,例如-123 --> -321
- 19.设计实现遍历目录与子目录,抓取.pyc文件
- 20.一行代码实现1-100之和
- 21.Python-遍历列表时删除元素的正确做法
- 22.字符串的操作题目
- 23.可变类型和不可变类型
- 24.is和==有什么区别?
- 25.求出列表所有奇数并构造新列表
- 26.用一行python代码写出1+2+3+10248
- 27.Python中变量的作用域?(变量查找顺序)
- 28.字符串
"123"转换成123,不使用内置api,例如int() - 29.Given an array of integers
- 30.python代码实现删除一个list里面的重复元素
- 31.统计一个文本中单词频次最高的10个单词?
- 32.请写出一个函数满足以下条件
- 33.使用单一的列表生成式来产生一个新的列表
- 34.用一行代码生成[1,4,9,16,25,36,49,64,81,100]
- 35.输入某年某月某日,判断这一天是这一年的第几天?
- 36.两个有序列表,l1,l2,对这两个列表进行合并不可使用extend
- 37.给定一个任意长度数组,实现一个函数
- 38.写一个函数找出一个整数数组中,第二大的数
- 39.阅读一下代码他们的输出结果是什么?
- 40.统计一段字符串中字符出现的次数
- 41.super函数的具体用法和场景
- Python高级
- 元类
- 内存管理与垃圾回收机制
- 函数
- 52.python常见的列表推导式?
- 53.简述read、readline、readlines的区别?
- 54.什么是Hash(散列函数)?
- 55.python函数重载机制?
- 56.写一个函数找出一个整数数组中,第二大的数
- 57.手写一个判断时间的装饰器
- 58.使用Python内置的filter()方法来过滤?
- 59.编写函数的4个原则
- 60.函数调用参数的传递方式是值传递还是引用传递?
- 61.如何在function里面设置一个全局变量
- 62.对缺省参数的理解 ?
- 63.Mysql怎么限制IP访问?
- 64.带参数的装饰器?
- 65.为什么函数名字可以当做参数用?
- 66.Python中pass语句的作用是什么?
- 67.有这样一段代码,print c会输出什么,为什么?
- 68.交换两个变量的值?
- 69.map函数和reduce函数?
- 70.回调函数,如何通信的?
- 71.Python主要的内置数据类型都有哪些? print dir( ‘a ’) 的输出?
- 72.map(lambda x:xx,[y for y in range(3)])的输出?
- 73.hasattr() getattr() setattr() 函数使用详解?
- 74.一句话解决阶乘函数?
- 75.什么是lambda函数? 有什么好处?
- 7 4CB8 6.递归函数停止的条件?
- 77.下面这段代码的输出结果将是什么?请解释。
- 78.什么是lambda函数?它有什么好处?写一个匿名函数求两个数的和
- 设计模式
- 面向对象
- 正则表达式
- 94.请写出一段代码用正则匹配出ip?
- 95.a = “abbbccc”,用正则匹配为abccc,不管有多少b,就出现一次?
- 96.Python字符串查找和替换?
- 97.用Python匹配HTML g tag的时候,<.> 和 <.*?> 有什么区别
- 98.正则表达式贪婪与非贪婪模式的区别?
- 99.写出开头匹配字母和下划线,末尾是数字的正则表达式?
- 100.正则表达式操作
- 101.请匹配出变量A 中的json字符串。
- 102.怎么过滤评论中的表情?
- 103.简述Python里面search和match的区别
- 104.请写出匹配ip的Python正则表达式
- 105.Python里match与search的区别?
- 系统编程
- 106.进程总结
- 107.谈谈你对多进程,多线程,以及协程的理解,项目是否用?
- 108.Python异常使用场景有那些?
- 109.多线程共同操作同一个数据互斥锁同步?
- 110.什么是多线程竞争?
- 111.请介绍一下Python的线程同步?
- 112.解释以下什么是锁,有哪几种锁?
- 113.什么是死锁?
- 114.多线程交互访问数据,如果访问到了就不访问了?
- 115.什么是线程安全,什么是互斥锁?
- 116.说说下面几个概念:同步,异步,阻塞,非阻塞?
- 117.什么是僵尸进程和孤儿进程?怎么避免僵尸进程?
- 118.python中进程与线程的使用场景?
- 119.线程是并发还是并行,进程是并发还是并行?
- 120.并行(parallel)和并发(concurrency)?
- 121.IO密集型和CPU密集型区别?
- 122.python asyncio的原理?
- 网络编程
- 123.怎么实现强行关闭客户端和服务器之间的连接?
- 124.简述TCP和UDP的区别以及优缺点?
- 125.简述浏览器通过WSGI请求动态资源的过程?
- 126.描述用浏览器访问www.baidu.com的过程
- 127.Post和Get请求的区别?
- 128.cookie 和session 的区别?
- 129.列出你知道的HTTP协议的状态码,说出表示什么意思?
- 130.请简单说一下三次握手和四次挥手?
- 131.说一下什么是tcp的2MSL?
- 132.为什么客户端在TIME-WAIT状态必须等待2MSL的时间?
- 133.说说HTTP和HTTPS区别?
- 134.谈一下HTTP协议以及协议头部中表示数据类型的字段?
- 135.HTTP请求方法都有什么?
- 136.使用Socket套接字需要传入哪些参数 ?
- 137.HTTP常见请求头?
- 138.七层模型?
- 139.url的形式?
- Web
- Flask
- Django
- 142.什么是wsgi,uwsgi,uWSGI?
- 143.Django、Flask、Tornado的对比?
- 144.CORS 和 CSRF的区别?
- 145.Session,Cookie,JWT的理解
- 146.简述Django请求生命周期
- 147.用的restframework完成api发送时间时区
- 148.nginx,tomcat,apach到都是什么?
- 149.请给出你熟悉关系数据库范式有哪些,有什么作用?
- 150.简述QQ登陆过程
- 151.post 和 get的区别?
- 152.项目中日志的作用
- 153.django中间件的使用?
- 154.谈一下你对uWSGI和nginx的理解?
- 155.Python中三大框架各自的应用场景?
- 156.Django中哪里用到了线程?哪里用到了协程?哪里用到了进程?
- 157.有用过Django REST framework吗?
- 158.对cookies与session的了解?他们能单独用吗?
- 爬虫
- 159.试列出至少三种目前流行的大型数据库
- 160.列举您使用过的Python网络爬虫所用到的网络数据包?
- 161.爬取数据后使用哪个数据库存储数据的,为什么?
- 162.你用过的爬虫框架或者模块有哪些?优缺点?
- 163.写爬虫是用多进程好?还是多线程好?
- 164.常见的反爬虫和应对方法?
- 165.解析网页的解析器使用最多的是哪几个?
- 166.需要登录的网页,如何解决同时限制ip,cookie,session
- 167.验证码的解决?
- 168.使用最多的数据库,对他们的理解?
- 169.编写过哪些爬虫中间件?
- 170.“极验”滑动验证码如何破解?
- 171.爬虫多久爬一次,爬下来的数据是怎么存储?
- 172.cookie过期的处理问题?
- 173.动态加载又对及时性要求很高怎么处理?
- 174.HTTPS有什么优点和缺点?
- 175.HTTPS是如何实现安全传输数据的?
- 176.TTL,MSL,RTT各是什么?
- 177.谈一谈你对Selenium和PhantomJS了解
- 178.平常怎么使用代理的 ?
- 179.存放在数据库(redis、mysql等)。
- 180.怎么监控爬虫的状态?
- 181.描述下scrapy框架运行的机制?
- 182.谈谈你对Scrapy的理解?
- 183.怎么样让 scrapy 框架发送一个 post 请求(具体写出来)
- 184.怎么监控爬虫的状态 ?
- 185.怎么判断网站是否更新?
- 186.图片、视频爬取怎么绕过防盗连接
- 187.你爬出来的数据量大概有多大?大概多长时间爬一次?
- 188.用什么数据库存爬下来的数据?部署是你做的吗?怎么部署?
- 189.增量爬取
- 190.爬取下来的数据如何去重,说一下scrapy的具体的算法依据。
- 191.Scrapy的优缺点?
- 192.怎么设置爬取深度?
- 193.scrapy和scrapy-redis有什么区别?为什么选择redis数据库?
- 194.分布式爬虫主要解决什么问题?
- 195.什么是分布式存储?
- 196.你所知道的分布式爬虫方案有哪些?
- 197.scrapy-redis,有做过其他的分布式爬虫吗?
- 数据库
- MySQL
- Redis
- MongoDB
- 测试
- 数据结构
- 222.数组中出现次数超过一半的数字-Python版
- 223.求100以内的质数
- 224.无重复字符的最长子串-Python实现
- 225.通过2个5/6升得水壶从池塘得到3升水
- 226.什么是MD5加密,有什么特点?
- 227.什么是对称加密和非对称加密
- 228.冒泡排序的思想?
- 229.快速排序的思想?
- 230.如何判断单向链表中是否有环?
- 231.你知道哪些排序算法(一般是通过问题考算法)
- 232.斐波那契数列
- 233.如何翻转一个单链表?
- 234.青蛙跳台阶问题
- 235.两数之和 Two Sum
- 236.搜索旋转排序数组 Search in Rotated Sorted Array
- 237.Python实现一个Stack的数据结构
- 238.写一个二分查找
- 239.set 用 in 时间复杂度是多少,为什么?
- 240.列表中有n个正整数范围在[0,1000],进行排序;
- 241.面向对象编程中有组合和继承的方法实现新的类
- 大数据
def get_lines():
with open('file.txt','rb') as f:
return f.readlines()
if __name__ == '__main__':
for e in get_lines():
process(e) # 处理每一行数据现在要处理一个大小为10G的文件,但是内存只有4G,如果在只修改get_lines 函数而其他代码保持不变的情况下,应该如何实现?需要考虑的问题都有那些?
def get_lines():
with open('file.txt','rb') as f:
for i in f:
yield i个人认为:还是设置下每次返回的行数较好,否则读取次数太多。
def get_lines():
l = []
with open('file.txt','rb') as f:
data = f.readlines(60000)
l.append(data)
yield l
Pandaaaa906提供的方法
from mmap import mmap
def get_lines(fp):
with open(fp,"r+") as f:
m = mmap(f.fileno(), 0)
tmp = 0
for i, char in enumerate(m):
if char==b"\n":
yield m[tmp:i+1].decode()
tmp = i+1
if __name__=="__main__":
for i in get_lines("fp_some_huge_file"):
print(i)要考虑的问题有:内存只有4G无法一次性读入10G文件,需要分批读入分批读入数据要记录每次读入数据的位置。分批每次读取数据的大小,太小会在读取操作花费过多时间。 https://stackoverflow.com/questions/30294146/python-fastest-way-to-process-large-file
def print_directory_contents(sPath):
"""
这个函数接收文件夹的名称作为输入参数
返回该文件夹中文件的路径
以及其包含文件夹中文件的路径
"""
import os
for s_child in os.listdir(s_path):
s_child_path = os.path.join(s_path, s_child)
if os.path.isdir(s_child_path):
print_directory_contents(s_child_path)
else:
print(s_child_path)import datetime
def dayofyear():
year = input("请输入年份: ")
month = input("请输入月份: ")
day = input("请输入天: ")
date1 = datetime.date(year=int(year),month=int(month),day=int(day))
date2 = datetime.date(year=int(year),month=1,day=1)
return (date1-date2).days+1import random
alist = [1,2,3,4,5]
random.shuffle(alist)
print(alist)sorted(d.items(),key=lambda x:x[1])x[0]代表用key进行排序;x[1]代表用value进行排序。
d = {key:value for (key,value) in iterable}print("aStr"[::-1])str1 = "k:1|k1:2|k2:3|k3:4"
def str2dict(str1):
dict1 = {}
for iterms in str1.split('|'):
key,value = iterms.split(':')
dict1[key] = value
return dict1
#字典推导式
d = {k:int(v) for t in str1.split("|") for k, v in (t.split(":"), )}alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
def sort_by_age(list1):
return sorted(alist,key=lambda x:x['age'],reverse=True)list = ['a','b','c','d','e']
print(list[10:])代码将输出[],不会产生IndexError错误,就像所期望的那样,尝试用超出成员的个数的index来获取某个列表的成员。例如,尝试获取list[10]和之后的成员,会导致IndexError。然而,尝试获取列表的切片,开始的index超过了成员个数不会产生IndexError,而是仅仅返回一个空列表。这成为特别让人恶心的疑难杂症,因为运行的时候没有错误产生,导致Bug很难被追踪到。
print([x*11 for x in range(10)])list1 = [1,2,3]
list2 = [3,4,5]
set1 = set(list1)
set2 = set(list2)
print(set1 & set2)
print(set1 ^ set2)l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
print(l2)用list类的sort方法:
l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)也可以这样写:
l1 = ['b','c','d','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print(l2)也可以用遍历:
l1 = ['b','c','d','c','a','a']
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
print(l2)A,B 中相同元素: print(set(A)&set(B))
A,B 中不同元素: print(set(A)^set(B))a. 在python里凡是继承了object的类,都是新式类
b. Python3里只有新式类
c. Python2里面继承object的是新式类,没有写父类的是经典类
d. 经典类目前在Python里基本没有应用
e. 保持class与type的统一对新式类的实例执行a.__class__与type(a)的结果是一致的,对于旧式类来说就不一样了。
f.对于多重继承的属性搜索顺序不一样新式类是采用广度优先搜索,旧式类采用深度优先搜索。
a. 整型 int、 长整型 long、浮点型 float、 复数 complex
b. 字符串 str、 列表 list、 元祖 tuple
c. 字典 dict 、 集合 set
d. Python3 中没有 long,只有无限精度的 int
第一种方法:使用装饰器
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True第二种方法:使用基类 New 是真正创建实例对象的方法,所以重写基类的new 方法,以此保证创建对象的时候只生成一个实例
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # True第三种方法:元类,元类是用于创建类对象的类,类对象创建实例对象时一定要调用call方法,因此在调用call时候保证始终只创建一个实例即可,type是python的元类
class Singleton(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
# Python2
class Foo(object):
__metaclass__ = Singleton
# Python3
class Foo(metaclass=Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2) # Trueclass Solution(object):
def reverse(self,x):
if -10<x<10:
return x
str_x = str(x)
if str_x[0] !="-":
str_x = str_x[::-1]
x = int(str_x)
else:
str_x = str_x[1:][::-1]
x = int(str_x)
x = -x
return x if -2147483648<x<2147483647 else 0
if __name__ == '__main__':
s = Solution()
reverse_int = s.reverse(-120)
print(reverse_int)第一种方法:
import os
def get_files(dir,suffix):
res = []
for root,dirs,files in os.walk(dir):
for filename in files:
name,suf = os.path.splitext(filename)
if suf == suffix:
res.append(os.path.join(root,filename))
print(res)
get_files("./",'.pyc')第二种方法:
import os
def pick(obj):
if obj.endswith(".pyc"):
print(obj)
def scan_path(ph):
file_list = os.listdir(ph)
for obj in file_list:
if os.path.isfile(obj):
pick(obj)
elif os.path.isdir(obj):
scan_path(obj)
if __name__=='__main__':
path = input('输入目录')
scan_path(path)第三种方法
from glob import iglob
def func(fp, postfix):
for i in iglob(f"{fp}/**/*{postfix}", recursive=True):
print(i)
if __name__ == "__main__":
postfix = ".pyc"
func("K:\Python_script", postfix)count = sum(range(0,101))
print(count)遍历在新在列表操作,删除时在原来的列表操作
a = [1,2,3,4,5,6,7,8]
print(id(a))
print(id(a[:]))
for i in a[:]:
if i>5:
pass
else:
a.remove(i)
print(a)
print('-----------')
print(id(a))#filter
a=[1,2,3,4,5,6,7,8]
b = filter(lambda x: x>5,a)
print(list(b))列表解析
a=[1,2,3,4,5,6,7,8]
b = [i for i in a if i>5]
print(b)倒序删除 因为列表总是‘向前移’,所以可以倒序遍历,即使后面的元素被修改了,还没有被遍历的元素和其坐标还是保持不变的
a=[1,2,3,4,5,6,7,8]
print(id(a))
for i in range(len(a)-1,-1,-1):
if a[i]>5:
pass
else:
a.remove(a[i])
print(id(a))
print('-----------')
print(a)全字母短句 PANGRAM 是包含所有英文字母的句子,比如:A QUICK BROWN FOX JUMPS OVER THE LAZY DOG. 定义并实现一个方法 get_missing_letter, 传入一个字符串采纳数,返回参数字符串变成一个 PANGRAM 中所缺失的字符。应该忽略传入字符串参数中的大小写,返回应该都是小写字符并按字母顺序排序(请忽略所有非 ACSII 字符)
下面示例是用来解释,双引号不需要考虑:
(0)输入: "A quick brown for jumps over the lazy dog"
返回: ""
(1)输入: "A slow yellow fox crawls under the proactive dog"
返回: "bjkmqz"
(2)输入: "Lions, and tigers, and bears, oh my!"
返回: "cfjkpquvwxz"
(3)输入: ""
返回:"abcdefghijklmnopqrstuvwxyz"
def get_missing_letter(a):
s1 = set("abcdefghijklmnopqrstuvwxyz")
s2 = set(a.lower())
ret = "".join(sorted(s1-s2))
return ret
print(get_missing_letter("python"))
# other ways to generate letters
# range("a", "z")
# 方法一:
import string
letters = string.ascii_lowercase
# 方法二:
letters = "".join(map(chr, range(ord('a'), ord('z') + 1)))1,可变类型有list,dict.不可变类型有string,number,tuple.
2,当进行修改操作时,可变类型传递的是内存中的地址,也就是说,直接修改内存中的值,并没有开辟新的内存。
3,不可变类型被改变时,并没有改变原内存地址中的值,而是开辟一块新的内存,将原地址中的值复制过去,对这块新开辟的内存中的值进行操作。
is:比较的是两个对象的id值是否相等,也就是比较俩对象是否为同一个实例对象。是否指向同一个内存地址
== : 比较的两个对象的内容/值是否相等,默认会调用对象的eq()方法
a = [1,2,3,4,5,6,7,8,9,10]
res = [ i for i in a if i%2==1]
print(res)from functools import reduce
#1.使用sum内置求和函数
num = sum([1,2,3,10248])
print(num)
#2.reduce 函数
num1 = reduce(lambda x,y :x+y,[1,2,3,10248])
print(num1)函数作用域的LEGB顺序
1.什么是LEGB?
L: local 函数内部作用域
E: enclosing 函数内部与内嵌函数之间
G: global 全局作用域
B: build-in 内置作用
python在函数里面的查找分为4种,称之为LEGB,也正是按照这是顺序来查找的
方法一: 利用 str 函数
def atoi(s):
num = 0
for v in s:
for j in range(10):
if v == str(j):
num = num * 10 + j
return num方法二: 利用 ord 函数
def atoi(s):
num = 0
for v in s:
num = num * 10 + ord(v) - ord('0')
return num方法三: 利用 eval 函数
def atoi(s):
num = 0
for v in s:
t = "%s * 1" % v
n = eval(t)
num = num * 10 + n
return num方法四: 结合方法二,使用 reduce,一行解决
from functools import reduce
def atoi(s):
return reduce(lambda num, v: num * 10 + ord(v) - ord('0'), s, 0)给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。示例:给定nums = [2,7,11,15],target=9 因为 nums[0]+nums[1] = 2+7 =9,所以返回[0,1]
class Solution:
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = {}
size = 0
while size < len(nums):
if target-nums[size] in d:
if d[target-nums[size]] <size:
return [d[target-nums[size]],size]
else:
d[nums[size]] = size
size = size +1
solution = Solution()
list = [2,7,11,15]
target = 9
nums = solution.twoSum(list,target)
print(nums)
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
num = target - nums[i]
if num in nums[i+1:]:
return [i, nums.index(num,i+1)]
给列表中的字典排序:假设有如下list对象,alist=[{"name":"a","age":20},{"name":"b","age":30},{"name":"c","age":25}],将alist中的元素按照age从大到小排序 alist=[{"name":"a","age":20},{"name":"b","age":30},{"name":"c","age":25}]
alist_sort = sorted(alist,key=lambda e: e.__getitem__('age'),reverse=True)def distFunc1(a):
"""使用集合去重"""
a = list(set(a))
print(a)
def distFunc2(a):
"""将一个列表的数据取出放到另一个列表中,中间作判断"""
list = []
for i in a:
if i not in list:
list.append(i)
#如果需要排序的话用sort
list.sort()
print(list)
def distFunc3(a):
"""使用字典"""
b = {}
b = b.fromkeys(a)
c = list(b.keys())
print(c)
if __name__ == "__main__":
a = [1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
distFunc1(a)
distFunc2(a)
distFunc3(a)
import re
# 方法一
def test(filepath):
distone = {}
with open(filepath) as f:
for line in f:
line = re.sub("\W+", " ", line)
lineone = line.split()
for keyone in lineone:
if not distone.get(keyone):
distone[keyone] = 1
else:
distone[keyone] += 1
num_ten = sorted(distone.items(), key=lambda x:x[1], reverse=True)[:10]
num_ten =[x[0] for x in num_ten]
return num_ten
# 方法二
# 使用 built-in 的 Counter 里面的 most_common
import re
from collections import Counter
def test2(filepath):
with open(filepath) as f:
return list(map(lambda c: c[0], Counter(re.sub("\W+", " ", f.read()).split()).most_common(10)))