2020版110道python面试题

01、一行代码实现1-100之和:

>>> print(sum(i for i in range(101)))
5050
>>> 

02、如何在一个函数内部修改全局变量:

>>>a = 123456
>>>def A():
		global a
		a = 521
>>>A()
>>>print(a)
结果:521

03、列出5个python标准库:

  1. os:提供与操作系统相关联的函数
  2. sys:用于命令行参数
  3. re:用于正则表达式
  4. math:数学运算
  5. datetime:处理日期时间

04、字典如何删除键和合并两个字典:
(1)删除:

>>>d1 = {'usr':'root','pwd':'1234'}
>>>del d1['usr']
>>>print(d1)
d1 = {'pwd':'1234'}

(2)合并
1>dict(d1.items() + dict(d2.item()))方法。如:

>>>d1 = {'usr':'root','pwd':'1234'}
>>>d2 = {'ip':'127.0.0.0','port':'8080'}
>>>d3 = dict(d1.items()+d2.items())
>>>d3
{'ip':'127.0.0.0','pwd':'1234','usr':'root','port''8080'}

其中:
d1.items() 获取字典的键值对的列表
d1.items()+d2.items()拼成一个新的列表
dict(d1.ite-ms()+d2.items())将合并成的列表转变成新的字典
2> 借助字典的update()方法。如:

>>>d1 = {'usr':'root','pwd':'1234'}
>>>d2 = {'ip':'127.0.0.0','port':'8080'}
>>>d3 = {}
>>>d3.update(d1)
>>>d3.update(d2)
>>>d3
{'ip':'127.0.0.0','pwd':'1234','usr':'root','port''8080'}
或者:
>>>d3 = d1.copy()
>>>d3.update(d2)
>>>d3
{'ip':'127.0.0.0','pwd':'1234','usr':'root','port''8080'}

3> 借助字典dict(d1,**d2)方法

>>>d1 = {'usr':'root','pwd':'1234'}
>>>d2 = {'ip':'127.0.0.0','port':'8080'}
>>>d3 = dict{d1,**d2}
>>>d3	{'ip':'127.0.0.0','pwd':'1234','usr':'root','port''8080'}

4> 借助字典

>>>d1 = {'usr':'root','pwd':'1234'}
>>>d2 = {'ip':'127.0.0.0','port':'8080'}
>>>d3 = {}
>>>for k,v in d1.items():
		d3[k] = v
>>>for k,v in d2.items():
			d3[k] = v
>>>d3
{'ip':'127.0.0.0','pwd':'1234','usr':'root','port''8080'}

05、谈下python的GIL:
GIL是python的全局解释器锁。一个线程在运行python程序的时候会独占python解释器(给给线程加了一把锁即GIL),使进程内的其他线程无法进行,只有等该线程运行完全后其他进程才能运行。如果线程运行过程中碰到耗时操作,解释器锁会解开,使其他线程运行。因此在多进程中,线程的运行是并行的。多进程中每一个进程都能被系统分配资源,相当于每个进程有一个python解释器。因此多进程可以实现多个进程的并行,缺点是进程系统资源开销大。

06、python实现列表去重方法:
(1)使用set集合,因为使用集合可以去除元素。先使用set转为集合,然后再使用list将集合再变回列表。

>>> alist = [1,2,3,3,4,4,6,7]
>>> b = set(alist)
>>> print(list(b))
[1, 2, 3, 4, 6, 7]

(2)考虑先对列表进行遍历,然后新建一个空列表,对原有的列表进行遍历,判断该元素是否在列表中;如果不在,就将该元素添加到新建的列表中,这样得到的新列表就满足要求了。

>>> alist = [1,2,3,3,4,4,6,7]
>>> b = list()
>>> for i in alist:
	if i not in b:
		b.append(i)
>>> print(b)
[1, 2, 3, 4, 6, 7]

7、fun(args,**kwargs)中的args、**kwarg什么意思?
(1)*args是用来发送一个键值对可变数量的参数表给另一个函数,意思就是没有key值。如:

>>> def hello(hello,*args):
		print("hello:",hello)
		for x in args:
			print("arg:",x)
>>> hello(1,2,3,4)
hello: 1
arg: 2
arg: 3
arg: 4

(2)**kwargs将不定长度的键值对作为参数传递给一个函数,意思就是有一个key值。如:

>>> def hello(hello,**kwargs):
		print("hello:",hello)
		for x in kwargs:
			print("%s:%s"%(key,kwargs[key]))
>>>hello(arg=1,arg2=2,arg3=3)
>>>arg:1
>>>arg2:2
>>>arg3:3

8、python2和python3的range(100)的区别:
1>python2中range返回的是一个列表。
2>python3中的renge返回的是一个迭代值,节省内存。

9、一句话解释什么样的语言能够用装饰器:
函数能够作为参数传递的语言,能够使用装饰器。

10、python内置的数据类型有哪些?

  1. 整型(数字int):
    1>int 有符号整型
    2>long 长整型
    3>float 浮点型
    4>complex 复数
  2. 布尔型(bool) 用True或者False表示值
  3. 字符串类型(str)
  4. 列表(list) 用【】表示
  5. 元组(tuple) 用()表示
  6. 字典(dict) 用{}表示

11、简述面向对象中__new__和__init__区别:
(1)__new__方法:类级别的方法:
特性:

  1. 是在类准备将自身实例化时调用,并且至少需要传递一个参数cls,此参数在实例化时由python解释器提供;
  2. 始终是类的静态方法,即使没有加上静态方法装饰器。
  3. 必须要有返回值,返回实例化出来的实例;在自己__new__()时需要注意:
    可以使用return父类.new__出来的实例。
  4. 如:
>>> class A(object):
	def __new__(cls):
		return "abc"
>>> a = A()
>>> print(a)
abc
>>> print(type(a))
<class 'str'>

(2)_init_方法:实例级别的方法:
特性:

  1. 有一个参数self,该self参数就是__new__()返回的实例。
  2. init()在_new()的基础上完成初始化动作,不需要返回值。
  3. 若__new__()没有正确返回当前类cls的实例额,那__init__()将不会被调用。
  4. 创建的每一个实例都有自己的属性,方便类中实例方法调用。
  5. 如:
>>> class B():
	def __new__(cls):
		print("__new__方法被执行")
		return super(B,cls).__new__(cls)
	def __init__(self):
		print("__init__方法被执行")
>>> b = B()
__new__方法被执行
__init__方法被执行

12、简述with方法打开处理文件帮我们做了什么?
with方法帮我们实现了finally中的f.close。

13、列表【1,2,3,4,5],使用map()函数输出[1,4,9,16,25],并使用列表推导式提取出大与10的数,最终输出[16,25]。
1 . map()函数第一个参数是fun,第二个参数一般是list,第三个参数是list(可不写)。
2. 代码如下:

>>> list = [1,2,3,4,5,6,7]
>>> def fn(x):
	return x**2

>>> res = map(fn,list)
>>> res = [i for i in res if i > 10]
>>> print(res)
[16, 25, 36, 49]

14、python中生成随机整数、随机小数、0–1之间小数方法。

  1. 随机整数:random.randint(a,b),生成区间内的整数
    随机小数:使用numpy库,利用np.random.randn(5)生成5个随机小数
    0-1随机小数:random.random(),括号不传递参数
    2.`在这里插入代码片
>>> # 生成随机整数
>>> import random
>>> print(random.randint(1,100))
83
>>>

15、避免转义给字符号串加哪个字母表示原始字符串?
r,表示需要转义原始字符串,不转义特殊字符串。

16、

中国
,用正则匹配出标签里面的内容(“中国”),其中class的类名是不确定的。

>>> import re
>>> str = '
中国
'
>>> res = re.findall(r'
(.*?)
'
,str) >>> print(res) ['中国'] >>>

17、python中断言方法举例:

  1. assert()方法,断言成功,则程序继续执行;断言失败,则程序报错。
  2. 代码如下:
>>> a = 3
>>> assert(a>1)
>>> print("断言成功,程序继续往下执行")
断言成功,程序继续往下执行
>>> b = 4
>>> assert (b > 7)
Traceback (most recent call last):
  File "", line 1, in <module>
    assert (b > 7)
AssertionError

18、数据表student有id,name,score,city字段,其中name中的名字可有重复,需要消除重复行,请写sql语句。

select distinct name from student

19、10个linux常用命令:

ls pwd cd touch rm mkdir tree cp mv cat more grep echo

20、python2和python3区别?列举5个

  1. pyhton3 使用print必须以小括号包括打印的内容,比如 print(“hahahhh”)。
    pytho2既可以使用小括号的方式,也可以使用一个空格来分隔打印内容,比如 print “hahahhhh”。
  2. python2 range(1,10)返回列表,pyhton3中返回迭代器,节约内存。
  3. python2使用ASCII编码,python3使用utf-8编码。
  4. python2中unicode表示字符串序列,str表示字节序列。
    python3中str表示字符串序列,byte表示字节序列。
    5.python2中为正常显示中文,引入coding声明,python3中不需要。
  5. python2中是raw_input()函数,python3中是input()函数。

21、列出python中可变数据类型和不可变数据类型,并简述原理:

  1. 不可变数据类型:
    1>不可变数据类型:数值型、字符串string和元组tuple。
    2>不可变数据类型:是指不允许变量的值发生变化,如果改变了变量的值,相当于是新建了一个对象;而对于相同的值的对象,在内存中则只有一个对象地址。如:
>>> a=3
>>> b=3
>>> id(a)
1821540528
>>> id(b)
1821540528
  1. 可变数据类型:
    1>包括列表list和字典dict
    2>可变数据类型:是指允许变量的值发生变化,即如果对变量进行append、+=等这种操作后,只是改变了变量的值,而不会新建一个对象,变量引用的对象的地址也不会变化;不过对于相同的值的不同对象,在内存中则会存在不同的对象,即每个对象都有自己的地址,相当于内存中对于同值的对象保存了多份,这里不存在引用计数,是实实在在的对象。如:
>>> a=[1,2]
>>> b=[1,2]
>>> id(a)
46043464
>>> id(b)
46048328

22、s = “ajldjlajfdljfddd”,去重并从小到大排序输出"adfjl"。
3. 原理:set去重,去重转换成list,利用sort方法进行排序,reverse=False是从小到大排序的。
4. 是不变数据类型,s.sort是没有返回值。
5. 代码 如下:

>>> s = "ajldjlajfdljfddd"
>>> s = set(s)
>>> s = list(s)
>>> s.sort(reverse = False)
>>> res = "".join(s)
>>> print(res)
adfjl

23、用lambda函数实现两个数相乘

>>> sum = lambda a,b: a*b
>>> print(sum(10,20))
200

24、字典根据键从小到大排序

# 按键(key)排序
def dictionairy():
    # 声明字典
    key_value = {}
    # 初始化
    key_value[7] = 56
    key_value[2] = 2
    key_value[6] = 12
    key_value[4] = 24
    key_value[8] = 18
    key_value[1] = 323
    print("按键(key)排序:")
    for i in sorted(key_value):
        print((i, key_value[i]), end="")
# 按值(value)排序
    print("按值(value排序:")
    print(sorted(key_value.items(),
            key= lambda kv:(kv[1],kv[0])))
def main():
    dictionairy()
if __name__ == "__main__":
    main()

25、利用collections库的Counter方法统计字符串每个单词出现的次数"kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"。

>>> from collections import Counter
>>> a = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
>>> b = Counter(a)
>>> print(b)
Counter({'l': 9, ';': 6, 'h': 6, 'f': 5, 'a': 4, 'j': 3, 'd': 3, 's': 2, 'k': 1, 'g': 1, 'b': 1})
>>> 

26、字符串a = “not 404 found 张三 99 深圳”,每个词中间是空格,用正则过滤掉英文和数字,最终输出"张三 深圳"。

>>> import re
>>> S = "not 404 found 张三 99 深圳"
>>> L = S.split(" ")
>>> res = re.findall("\d+|[a-zA-Z]+",S)
>>> tem = [item for item in L if not item in res]
>>> print(" ".join(tem))
张三 深圳

27、filter方法求出列表所有奇数并构造新列表,a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> def fn(a):
	return a % 2 == 1
>>> newlist = filter(fn,a)
>>> newlist = [i for i in newlist]
>>> print(newlist)
[1, 3, 5, 7, 9]

28、列表推导式求列表所有奇数并构造新列表,a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> a = [1,2,3,4,5,6,7,8,9,10]
>>> res = [i for i in a if i % 2 == 1]
>>> print(res)
[1, 3, 5, 7, 9]

29、正则re.complie作用
主要用来封装一个原本重复所使用的表达式

30、a=(1,)b=(1),c=(“1”) 分别是什么类型的数据?

>>> type((1))
<class 'int'>
>>> type(("1"))
<class 'str'>
>>> type((1,))
<class 'tuple'>
>>> 

31、两个列表[1,5,7,9]和[2,2,6,8]合并为[1,2,2,3,6,7,8,9]

>>> a = [1,5,7,9]
>>> b = [2,2,6,8]
>>> c = a + b
>>> c.sort()
>>> print(c)
[1, 2, 2, 5, 6, 7, 8, 9]

32、用python删除文件和用linux命令删除文件方法

python:os.remove(文件名)
linux:rm 文件名

33、log日志中,我们需要用时间戳记录error,warning等的发生时间,请用datetime模块打印当前时间戳 “2018-04-01 11:38:54”。

>>> import datetime
	>>> b = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+'星期:'+str(datetime.datetime.now().isoweekday())
	>>> print(b)
	2020-05-27 12:19:01星期:3
	>>> 

34、数据库优化查询方法
索引、外键、选择特定、联合查询、字段

35、请列出你会的任意一种统计图(条形图、折线图等)绘制的开源库,第三方也行
eastdraw、pycharm、matplotlib

36、写一段自定义异常代码

>>> def A():
	try:
		for i in range(5):
			if i > 3:
				raise Exception("数字太大了")
	except Exception as B:
		print(B)
>>> A()
数字太大了
>>> 

38、简述Django的orm

  1. ORM:对象关系映射(object relational mapping)。
  2. 作用:根据类生成表结构,将对象、列表的操作转换成对象的SQL语句,将SQL语句查询的结果转化成对象或者列表。
  3. 优点:极大的减轻开发人员的工作量,不需要面对因数据库的变更而导致代码的无效。修改代码则是在Django中出于model和数据库之间。

39、[[1,2],[3,4],[5,6]]一行代码展开该列表,得出[1,2,3,4,5,6]

>>> oldlist = [[1,2],[3,4],[5,6]]
>>> newlist = [j for i in old for j in i]
>>> print(newlist)
[1, 2, 3, 4, 5, 6]
>>> 

40、x=“abc”,y=“def”,z=[“d”,“e”,“f”],分别求出x.join(y)和x.join(z)返回的结果。

>>> x = "abc"
>>> y = "def"
>>> z =["d","e","f"]
>>> x.join(y)
'dabceabcf'
>>> x.join(z)
'dabceabcf'
>>>

41、举例说明异常模块中try except else finally的相关意义

try:
        # 尝试执行的代码
        pass
    except 错误类型1: 
        # 针对错误类型1,对应的代码处理
        pass
    except 错误类型2:
        # 针对错误类型2,对应的代码处理
        pass
    ...
    ...
    except Exception as result:  # 编程中很难一次排除所有的错误。这里相当于一个菜篮子,装了其他所有错误类型。
        print("未知类型错误:%s" % result)	# 打印错误信息
    else:
        # 没有异常才会执行的代码,作为奖励执行的代码
        pass
    finally:
        # 无论是否有异常,都会执行的代码
        print("无论是否有异常,都会执行的代码")

42、python中交换两个数值

>>> a,b = 1,2
>>> print(a,b)
1 2
>>> a,b = b,a
>>> print(a,b)
2 1
>>>

43、举例说明zip()函数用法

  1. zip()函数在运算时候,会以一个或者多个序列作为参数,返回一个列表。同事将这些序列中并排的元素配对。
  2. zip()参数可以接受任何类型的序列,同时也可以有两个以上的参数;当传入参数的长度不同的时候,zip自动以最短序列长度为准进行截取,获得元组。`
  3. 代码如下:
>>># 列表
>>> a = [10,20]
>>> b = [30,40]
>>> A = [i for i in zip(a,b)]
>>> print(A)
[(10, 30), (20, 40)]

>>># 元组
>>> a = (10,20)
>>> b = (30,40)
>>> A = [i for i in zip(a,b)]
>>> print(A)
[(10, 30), (20, 40)]

>>> # 字符串
>>> a = "abc"
>>> b = "cde"
>>> A = [i for i in zip(a,b)]
>>> print(A)
[('a', 'c'), ('b', 'd'), ('c', 'e')]
>>> 

44、a=“张明 98分”,用re.sub,将98替换为100

>>> import re
>>> a = "张明 98分"
>>> A = re.sub(r"\d+","100",a)
>>> print(A)
张明 100>>> 

45、写5条常用sql语句

  1. desc 表名;
  2. select *from 表名;
  3. show tables;
  4. show databases;
  5. delete from 表名 where id =*

46、a="hello"和b="你好"编码成bytes类型

47、[1,2,3]+[4,5,6]的结果是多少?

>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> 

48、提高python运行效率的方法

  1. 在排序时,尽可能多的使用键以及sort()方法
  2. 尝试多种编码
  3. 尽可能避免在循环中访问变量的属性
  4. 使用较新版本的python版本

49、简述mysql和redis区别

  1. mysql:关系型数据库,数据保存在磁盘中。检索的话,会有一定的输入输出操作,访问速度慢。
  2. redis:非关系型数据库,数据保存在内存中,速度快。

50、遇到bug如何处理

  1. 细节上的错误,通过print()打印,能执行到print()说明一般上面的代码没有问题;调试各行代码进行解决。
  2. 如果出现错误在第三方框架,查找官方文档或者百度一下。

51、正则匹配,匹配日期2018-03-20

  • List item

52、list=[2,3,5,4,9,6],从小到大排序,不许用sort,输出[2,3,4,5,6,9]

>>> list = [2,3,5,4,9,6]
>>> new_list = []
>>> def get_min(list):
		a = min(list)
		list.remove(a)
		new_list.append(a)
		if len(list) > 0:
			get_min(list)
		return new_list

>>> new_list = get_min(list)
>>> print(new_list)
	[2, 3, 4, 5, 6, 9]
	>>> 

53、写一个单列模式

>>> class Singleton(object):
	__A = None
	def __new__(cls,age,name):
		if not cls.__A:
			cls.__A = object.__new__(cls)
		return cls.__A

>>> a =Singleton(18,"huahua")
>>> b = Singleton(19,"shuishui")
>>> print(id(a))
45574688
>>> print(id(b))
45574688
>>> a.age = 20
>>> print(b.age)
20
>>> 

54、保留两位小数

>>> a = ("%.02f")%3.141592653
>>> print(a)
3.14
>>>

55、求三个方法打印结果

>>> def fn(k,v,dic={}):
dic[k] = v
print(dic)

>>> fn("one",1)
{'one': 1}
>>> fn("two",2)
{'one': 1, 'two': 2}
>>> fn("three",3,{})
{'three': 3}
>>> 

56、列出常见的状态码和意义

503 服务器超负载或停机维护
500 服务器故障或web应用故障
404 无法找到请求资源
403 请求资源被拒绝
401 需要通过http认证/认证失败
400 请求报文语法错误或参数错误
307 临时重定向,post不会变为get
304 发送附带条件请求为满足
303 期望使用get定向获取
302 临时重定向,资源已被临时分配
301 永久重定向,资源已永久被分配新的url

57、分别从前端、后端、数据库阐述web项目的性能优化

前端优化 减少http请求
后端优化 写代码时应该少用循环和判断语句;尽量多采用异步方式
数据库优化 尽量多使用索引、外键等

58、使用pop和del删除字典中的"name"字段,dic={“name”:“zs”,“age”:18}

>>> A = {"name":"sb","tel":138}
>>> A.pop("name")
'sb'
>>> 

59、列出常见MYSQL数据存储引擎

mylsam 插入数据快,空间和内存使用比较低
lnnodb 支持事务处理、外键、崩溃修复能力和并发控制
memory 所有数据在内存中、数据处理速度快、安全性不高

60、计算代码运行结果,zip函数历史文章已经说了,得出[(“a”,1),(“b”,2),(“c”,3),(“d”,4),(“e”,5)]

>>> A = zip(("a","b","c","d","e"),(1,2,3,4,5))
>>> A1 = dict(A)
>>> A2 = range(10)
>>> A3 = [i for i in A2 if i in A1]
>>> A4 = [A1[s] for s in A1]
>>> print("A1",A1)
A1 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

你可能感兴趣的:(python自学之路)