今天继续分享 Python 相关的面试题,在学习的路上,你我同行!
基础篇(二) 第一部分可以在这里查看,戳
1print("This is for %s" % "Python")
2print("This is for %s, and %s" %("Python", "You"))
output
1This is for Python
2This is for Python, and You
在 Python3 中,引入了这个新的字符串格式化方法。
1print("This is my {}".format("chat"))
2print("This is {name}, hope you can {do}".format(name="zhouluob", do="like"))
output
1This is my chat
2This is zhouluob, hope you can like
在 Python3-6 中,引入了这个新的字符串格式化方法。
1name = "luobodazahui"
2print(f"hello {name}")
output
1hello luobodazahui
一个复杂些的例子:
1def mytest(name, age):
2 return f"hello {name}, you are {age} years old!"
3people = mytest("luobo", 20)
4print(people)
output
1hello luobo, you are 20 years old!
1str1 = "hello world"
2print(str1.title())
3" ".join(list(map(lambda x: x.capitalize(), str1.split(" "))))
output
1Hello World
2'Hello World'
如:[1, 2, 3] -> ["1", "2", "3"]
1list1 = [1, 2, 3]
2list(map(lambda x: str(x), list1))
output
1['1', '2', '3']
如:("zhangfei", "guanyu"),(66, 80) -> {'zhangfei': 66, 'guanyu': 80}
1a = ("zhangfei", "guanyu")
2b = (66, 80)
3dict(zip(a,b))
output
1{'zhangfei': 66, 'guanyu': 80}
例子1:
1a = (1,2,3,[4,5,6,7],8)
2a[3] = 2
output
1---------------------------------------------------------------------------
2TypeError Traceback (most recent call last)
3<ipython-input-35-59469d550eb0> in <module>
4 1 a = (1,2,3,[4,5,6,7],8)
5----> 2 a[3] = 2
6 3 #a
7
8TypeError: 'tuple' object does not support item assignment
例子2:
1a = (1,2,3,[4,5,6,7],8)
2a[3][2] = 2
3a
output
1(1, 2, 3, [4, 5, 2, 7], 8)
从例子1的报错中也可以看出,tuple 是不可变类型,不能改变 tuple 里的元素,例子2中,list 是可变类型,改变其元素是允许的。
反射就是通过字符串的形式,导入模块;通过字符串的形式,去模块寻找指定函数,并执行。利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
简单理解就是用来判断某个字符串是什么,是变量还是方法
1class NewClass(object):
2 def __init__(self, name, male):
3 self.name = name
4 self.male = male
5 def myname(self):
6 print(f'My name is {self.name}')
7 def mymale(self):
8 print(f'I am a {self.male}')
9people = NewClass('luobo', 'boy')
10print(hasattr(people, 'name'))
11print(getattr(people, 'name'))
12setattr(people, 'male', 'girl')
13print(getattr(people, 'male'))
output
1True
2luobo
3girl
getattr,hasattr,setattr,delattr 对模块的修改都在内存中进行,并不会影响文件中真实内容。
使用 flask 构造 web 服务器
1from flask import Flask, request
2app = Flask(__name__)
3
4@app.route('/', methods=['POST'])
5def simple_api():
6 result = request.get_json()
7 return result
8
9
10if __name__ == "__main__":
11 app.run()
类与实例: 首先定义类以后,就可以根据这个类创建出实例,所以:先定义类,然后创建实例。 类与元类: 先定义元类, 根据 metaclass 创建出类,所以:先定义 metaclass,然后创建类。
1class MyMetaclass(type):
2 def __new__(cls, class_name, class_parents, class_attr):
3 class_attr['print'] = "this is my metaclass's subclass %s" %class_name
4 return type.__new__(cls, class_name, class_parents, class_attr)
5class MyNewclass(object, metaclass=MyMetaclass):
6 pass
7
8myinstance = MyNewclass()
9myinstance.print
output
1"this is my metaclass's subclass MyNewclass"
sort() 是可变对象列表(list)的方法,无参数,无返回值,sort() 会改变可变对象.
1dict1 = {'test1':1, 'test2':2}
2list1 = [2, 1, 3]
3print(list1.sort())
4list1
output
1None
2[1, 2, 3]
sorted() 是产生一个新的对象。sorted(L) 返回一个排序后的L,不改变原始的L。sorted() 适用于任何可迭代容器。
1dict1 = {'test1':1, 'test2':2}
2list1 = [2, 1, 3]
3print(sorted(dict1))
4print(sorted(list1))
output
1['test1', 'test2']
2[1, 2, 3]
GIL 是 Python 的全局解释器锁,同一进程中假如有多个线程运行,一个线程在运行 Python 程序的时候会占用 Python 解释器(加了一把锁即 GIL),使该进程内的其他线程无法运行,等该线程运行完后其他线程才能运行。如果线程运行过程中遇到耗时操作,则解释器锁解开,使其他线程运行。所以在多线程中,线程的运行仍是有先后顺序的,并不是同时进行。
1import random
2"".join(random.choice(string.printable[:-7]) for i in range(8))
output
1'd5^NdNJp'
1print('hello\nworld')
2print(b'hello\nworld')
3print(r'hello\nworld')
output
1hello
2world
3b'hello\nworld'
4hello\nworld
1list1 = [{'name': 'guanyu', 'age':29},
2 {'name': 'zhangfei', 'age': 28},
3 {'name': 'liubei', 'age':31}]
4sorted(list1, key=lambda x:x['age'])
output
1[{'name': 'zhangfei', 'age': 28},
2 {'name': 'guanyu', 'age': 29},
3 {'name': 'liubei', 'age': 31}]
all 如果存在 0 Null False 返回 False,否则返回 True;any 如果都是 0,None,False,Null 时,返回 True。
1print(all([1, 2, 3, 0]))
2print(all([1, 2, 3]))
3print(any([1, 2, 3, 0]))
4print(any([0, None, False]))
output
1False
2True
3True
4False
1def reverse_int(x):
2 if not isinstance(x, int):
3 return False
4 if -10 < x < 10:
5 return x
6 tmp = str(x)
7 if tmp[0] != '-':
8 tmp = tmp[::-1]
9 return int(tmp)
10 else:
11 tmp = tmp[1:][::-1]
12 x = int(tmp)
13 return -x
14reverse_int(-23837)
output
1-73832
首先判断是否是整数,再判断是否是一位数字,最后再判断是不是负数
函数式编程是一种抽象程度很高的编程范式,纯粹的函数式编程语言编写的函数没有变量,因此,任意一个函数,只要输入是确定的,输出就是确定的,这种纯函数称之为没有副作用。而允许使用变量的程序设计语言,由于函数内部的变量状态不确定,同样的输入,可能得到不同的输出,因此,这种函数是有副作用的。由于 Python 允许使用变量,因此,Python 不是纯函数式编程语言。
函数式编程的一个特点就是,允许把函数本身作为参数传入另一个函数,还允许返回一个函数!
函数作为返回值例子:
1def sum(*args):
2 def inner_sum():
3 tmp = 0
4 for i in args:
5 tmp += i
6 return tmp
7 return inner_sum
8mysum = sum(2, 4, 6)
9print(type(mysum))
10mysum()
output
1<class 'function'>
212
如果在一个内部函数里,对在外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认为是闭包(closure)。 附上函数作用域图片
闭包特点 1.必须有一个内嵌函数 2.内嵌函数必须引用外部函数中的变量 3.外部函数的返回值必须是内嵌函数
装饰器是一种特殊的闭包,就是在闭包的基础上传递了一个函数,然后覆盖原来函数的执行入口,以后调用这个函数的时候,就可以额外实现一些功能了。 一个打印 log 的例子:
1import time
2def log(func):
3 def inner_log(*args, **kw):
4 print("Call: {}".format(func.__name__))
5 return func(*args, **kw)
6 return inner_log
7
8
9@log
10def timer():
11 print(time.time())
12
13timer()
output
1Call: timer
21560171403.5128365
本质上,decorator就是一个返回函数的高阶函数
子程序切换不是线程切换,而是由程序自身控制 没有线程切换的开销,和多线程比,线程数量越多,协程的性能优势就越明显 不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁
斐波那契数列: 又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波纳契数列以如下被以递归的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)
生成器法:
1def fib(n):
2 if n == 0:
3 return False
4 if not isinstance(n, int) or (abs(n) != n): # 判断是正整数
5 return False
6 a, b = 0, 1
7 while n:
8 a, b = b, a+b
9 n -= 1
10 yield a
11
12[i for i in fib(10)]
output
1[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
递归法:
1def fib(n):
2 if n == 0:
3 return False
4 if not isinstance(n, int) or (abs(n) != n):
5 return False
6 if n <= 1:
7 return n
8 return fib(n-1)+ fib(n-2)
9
10[fib(i) for i in range(1, 11)]
output
1[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
1import re
2str1 = 'hello world:luobo dazahui'
3result = re.split(r":| ", str1)
4print(result)
output
1['hello', 'world', 'luobo', 'dazahui']
yield 是用来生成迭代器的语法,在函数中,如果包含了 yield,那么这个函数就是一个迭代器。当代码执行至 yield 时,就会中断代码执行,直到程序调用 next() 函数时,才会在上次 yield 的地方继续执行
1def foryield():
2 print("start test yield")
3 while True:
4 result = yield 5
5 print("result:", result)
6g = foryield()
7print(next(g))
8print("*"*20)
9print(next(g))
output
1start test yield
25
3********************
4result: None
55
可以看到,第一个调用 next() 函数,程序只执行到了 "result = yield 5" 这里,同时由于 yield 中断了程序,所以 result 也没有被赋值,所以第二次执行 next() 时,result 是 None。
1list1 = [2, 5, 8, 9, 3, 11]
2def paixu(data, reverse=False):
3 if not reverse:
4 for i in range(len(data) - 1):
5 for j in range(len(data) - 1 - i):
6 if data[j] > data[j+1]:
7 data[j], data[j+1] = data[j+1], data[j]
8 return data
9 else:
10 for i in range(len(data) - 1):
11 for j in range(len(data) - 1 - i):
12 if data[j] < data[j+1]:
13 data[j], data[j+1] = data[j+1], data[j]
14 return data
15
16print(paixu(list1, reverse=True))
output
1[11, 9, 8, 5, 3, 2]
快排的思想:首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序,之后再递归排序两边的数据。
挑选基准值:从数列中挑出一个元素,称为"基准"(pivot); 分割:重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(与基准值相等的数可以到任何一边)。在这个分割结束之后,对基准值的排序就已经完成; 递归排序子序列:递归地将小于基准值元素的子序列和大于基准值元素的子序列排序。
1list1 = [8, 5, 1, 3, 2, 10, 11, 4, 12, 20]
2def partition(arr,low,high):
3 i = ( low-1 ) # 最小元素索引
4 pivot = arr[high]
5
6 for j in range(low , high):
7
8 # 当前元素小于或等于 pivot
9 if arr[j] <= pivot:
10
11 i = i+1
12 arr[i],arr[j] = arr[j],arr[i]
13
14 arr[i+1],arr[high] = arr[high],arr[i+1]
15
16 return ( i+1 )
17
18def quicksort(arr,low,high):
19 if low < high:
20
21 pi = partition(arr,low,high)
22
23 quicksort(arr, low, pi-1)
24 quicksort(arr, pi+1, high)
25
26
27quicksort(list1, 0, len(list1)-1)
28
29print(list1)
output
1[1, 2, 3, 4, 5, 8, 10, 11, 12, 20]
该库是发起 HTTP 请求的强大类库,调用简单,功能强大。
1import requests
2
3url = "http://www.luobodazahui.top"
4
5
6response = requests.get(url) # 获得请求
7
8response.encoding = "utf-8" # 改变其编码
9
10html = response.text # 获得网页内容
11
12binary__content = response.content # 获得二进制数据
13
14raw = requests.get(url, stream=True) # 获得原始响应内容
15
16headers = {'user-agent': 'my-test/0.1.1'} # 定制请求头
17r = requests.get(url, headers=headers)
18
19cookies = {"cookie": "# your cookie"} # cookie的使用
20r = requests.get(url, cookies=cookies)
1dict1 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
2dict2 = {"zhangfei": 12, "guanyu": 13, "liubei": 18}
3def compare_dict(dict1, dict2):
4 issame = []
5 for k in dict1.keys():
6 if k in dict2:
7 if dict1[k] == dict2[k]:
8 issame.append(1)
9 else:
10 issame.append(2)
11 else:
12 issame.append(3)
13 print(issame)
14 sum_except = len(issame)
15 sum_actually = sum(issame)
16 if sum_except == sum_actually:
17 print("this two dict are same!")
18 return True
19 else:
20 print("this two dict are not same!")
21 return False
22
23test = compare_dict(dict1, dict2)
output
1[1, 1, 1]
2this two dict are same!
input() 函数
1def forinput():
2 input_text = input()
3 print("your input text is: ", input_text)
4forinput()
output
1hello
2your input text is: hello
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
1data1 = ['one', 'two', 'three', 'four']
2for i, enu in enumerate(data1):
3 print(i, enu)
output
10 one
21 two
32 three
43 four
pass 是空语句,是为了保持程序结构的完整性。pass 不做任何事情,一般用做占位语句。
1def forpass(n):
2 if n == 1:
3 pass
4 else:
5 print('not 1')
6forpass(1)
1import re
2email_list= ["test01@163.com","test02@163.123", ".test03g@qq.com", "test04@gmail.com" ]
3for email in email_list:
4 ret = re.match("[\w]{4,20}@(.*)\.com$",email)
5 if ret:
6 print("%s 是符合规定的邮件地址,匹配后结果是:%s" % (email,ret.group()))
7 else:
8 print("%s 不符合要求" % email)
9
output
1test01@163.com 是符合规定的邮件地址,匹配后结果是:test01@163.com
2test02@163.123 不符合要求
3.test03g@qq.com 不符合要求
4test04@gmail.com 是符合规定的邮件地址,匹配后结果是:test04@gmail.com
1str2 = 'werrQWSDdiWuW'
2counter = 0
3for i in str2:
4 if i.isupper():
5 counter += 1
6print(counter)
output
16
普通序列化:
1import json
2dict1 = {'name': '萝卜', 'age': 18}
3dict1_new = json.dumps(dict1)
4print(dict1_new)
output
1{"name": "\u841d\u535c", "age": 18}
保留中文
1import json
2dict1 = {'name': '萝卜', 'age': 18}
3dict1_new = json.dumps(dict1, ensure_ascii=False)
4print(dict1_new)
output
1{"name": "萝卜", "age": 18}
一个类继承自另一个类,也可以说是一个孩子类/派生类/子类,继承自父类/基类/超类,同时获取所有的类成员(属性和方法)。
继承使我们可以重用代码,并且还可以更方便地创建和维护代码。Python 支持以下类型的继承:
猴子补丁是指在运行时动态修改类和模块。 猴子补丁主要有以下几个用处:
help() 函数返回帮助文档和参数说明:
1help(dict)
output
1Help on class dict in module builtins:
2
3class dict(object)
4 | dict() -> new empty dictionary
5 | dict(mapping) -> new dictionary initialized from a mapping object's
6 | (key, value) pairs
7 | dict(iterable) -> new dictionary initialized as if via:
8 | d = {}
9 | for k, v in iterable:
10 | d[k] = v
11 | dict(**kwargs) -> new dictionary initialized with the name=value pairs
12 | in the keyword argument list. For example: dict(one=1, two=2)
13......
14
dir() 函数返回对象中的所有成员 (任何类型)
1dir(dict)
output
1['__class__',
2 '__contains__',
3 '__delattr__',
4 '__delitem__',
5 '__dir__',
6 '__doc__',
7 '__eq__',
8 '__format__',
9 '__ge__',
10 '__getattribute__',
11 '__getitem__',
12......
// 运算符执行地板除法,返回结果的整数部分 (向下取整) % 是取模符号,返回除法后的余数。 ** 符号表示取幂. a**b 返回 a 的 b 次方
1print(5//3)
2print(5/3)
3print(5%3)
4print(5**3)
output
11
21.6666666666666667
32
4125
使用 raise
1def test_raise(n):
2 if not isinstance(n, int):
3 raise Exception('not a int type')
4 else:
5 print('good')
6test_raise(8.9)
output
1---------------------------------------------------------------------------
2Exception Traceback (most recent call last)
3<ipython-input-262-b45324f5484e> in <module>
4 4 else:
5 5 print('good')
6----> 6 test_raise(8.9)
7
8<ipython-input-262-b45324f5484e> in test_raise(n)
9 1 def test_raise(n):
10 2 if not isinstance(n, int):
11----> 3 raise Exception('not a int type')
12 4 else:
13 5 print('good')
14
15Exception: not a int type
1tuple1 = (1, 2, 3, 4)
2list1 = list(tuple1)
3print(list1)
4tuple2 = tuple(list1)
5print(tuple2)
output
1[1, 2, 3, 4]
2(1, 2, 3, 4)
Python 的断言就是检测一个条件,如果条件为真,它什么都不做;反之它触发一个带可选错误信息的 AssertionError。
1def testassert(n):
2 assert n == 2, "n is not 2"
3 print('n is 2')
4testassert(1)
output
1---------------------------------------------------------------------------
2AssertionError Traceback (most recent call last)
3<ipython-input-268-a9dfd6c79e73> in <module>
4 2 assert n == 2, "n is not 2"
5 3 print('n is 2')
6----> 4 testassert(1)
7
8<ipython-input-268-a9dfd6c79e73> in testassert(n)
9 1 def testassert(n):
10----> 2 assert n == 2, "n is not 2"
11 3 print('n is 2')
12 4 testassert(1)
13
14AssertionError: n is not 2
同步异步指的是调用者与被调用者之间的关系。 所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不会返回,一旦调用返回,就得到了返回值。 异步的概念和同步相对。调用在发出之后,这个调用就直接返回了,所以没有返回结果。当该异步功能完成后,被调用者可以通过状态、通知或回调来通知调用者。
阻塞非阻塞是线程或进程之间的关系。 阻塞调用是指调用结果返回之前,当前线程会被挂起(如遇到io操作)。调用线程只有在得到结果之后才会返回。函数只有在得到结果之后才会将阻塞的线程激活。 非阻塞和阻塞的概念相对应,非阻塞调用指在不能立刻得到结果之前也会立刻返回,同时该函数不会阻塞当前线程。
Python 中的序列是有索引的,它由正数和负数组成。正的数字使用'0'作为第一个索引,'1'作为第二个索引,以此类推。 负数的索引从'-1'开始,表示序列中的最后一个索引,' - 2'作为倒数第二个索引,依次类推。
不是的,那些具有对象循环引用或者全局命名空间引用的变量,在 Python 退出时往往不会被释放。 另外不会释放 C 库保留的部分内容。
Flask 是 “microframework”,主要用来编写小型应用程序,不过随着 Python 的普及,很多大型程序也在使用 Flask。同时,在 Flask 中,我们必须使用外部库。 Django 适用于大型应用程序。它提供了灵活性,以及完整的程序框架和快速的项目生成方法。可以选择不同的数据库,URL结构,模板样式等。
1import os
2f = open('test.txt', 'w')
3f.close()
4os.listdir()
5os.remove('test.txt')
logging 模块是 Python 内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比 print,具备如下优点:
1import logging
2logging.debug("debug log")
3logging.info("info log")
4logging.warning("warning log")
5logging.error("error log")
6logging.critical("critica log")
output
1WARNING:root:warning log
2ERROR:root:error log
3CRITICAL:root:critica log
默认情况下,只显示了大于等于WARNING级别的日志。logging.basicConfig()函数调整日志级别、输出格式等。
1from collections import Counter
2str1 = "nihsasehndciswemeotpxc"
3print(Counter(str1))
output
1Counter({'s': 3, 'e': 3, 'n': 2, 'i': 2, 'h': 2, 'c': 2, 'a': 1, 'd': 1, 'w': 1, 'm': 1, 'o': 1, 't': 1, 'p': 1, 'x': 1})
re.compile 是将正则表达式编译成一个对象,加快速度,并重复使用。
try..except..else 没有捕获到异常,执行 else 语句 try..except..finally 不管是否捕获到异常,都执行 finally 语句
使用 re 正则替换
1import re
2str1 = '我是周萝卜,今年18岁'
3result = re.sub(r"\d+","20",str1)
4print(result)
output
我是周萝卜,今年20岁