今天总结一下python中常见的面试题:python
1.is与==的区别
is比较变量内存地址和值是否相等,==仅仅比较变量的值是否相等
须要注意:
当变量的值较小时(a=1, b=1时,a is b的值是True,这是因为python定义变量时底层的实现
决定的,例如小整数对象池)两个变量的id值就会相同,致使is的值为True。mysql
2.列表排序
sort():将原列表排序
soretd():生成新的一排序列表,原列表不变面试
In [47]: l1 Out[47]: [1, 4, 3, 8, 3] In [48]: sorted(l1) Out[48]: [1, 3, 3, 4, 8] In [49]: l1 Out[49]: [1, 4, 3, 8, 3] In [51]: l1.sort() In [52]: l1 Out[52]: [1, 3, 3, 4, 8]
sort()函数的应用:sql
# 按照info中字典的name排序 In [39]: info = [{"name": 'laownag', "age": 20}, {"name": 'laoli', "age": 21}, {"name": 'laoliu', "age": '23'}] # 使用参数key,参数值是一个函数 In [40]: info.sort(key=lambda x:x["name"]) In [41]: info Out[41]: [{'name': 'laoli', 'age': 21}, {'name': 'laoliu', 'age': '23'}, {'name': 'laownag', 'age': 20}]
sort()中的两个参数:
参数1:key,参数值是一个函数,依据这个函数排序
参数2:reverse,是否降序排列app
3.装饰器
现场写一个装饰器,好比:写一个装饰器,统计函数的执行时间,执行时间大于2秒的输出bad;不然输出good函数
import time def wrapper(func): def inner(): start = time.time() ret = func() end = time.time() if (end - start) > 1: print("bad") else: print("good") return inner
写一个装饰器,能够捕获函数忠执行的异常:code
def wrapper_cacth_exception(func): """ 捕获异常 :param func: :return: """ def wrapper(a, b): try: return func(a, b) except Exception as e: return e return wrapper
4.统计list中每一个值出现的次数,这个题目主要考察使用collections中的defaultdict对象
from collections import defaultdict users = ["wyzane1", "wyzane2", "wyzane3", "wyzane2"] default_dict = defaultdict(int) for user in users: default_dict[user] += 1 print(default_dict)
固然,还有另一种方法也能够:主要使用了dict中的setdefault方法排序
user_dict = {} for user in user: user_dict.setdefault(user, 0) user_dict[user] += 1 print(user_dict)
5.mysql经常使用引擎及区别
这个就本身百度吧。内存
6.enumerate的使用
for i in enumerate(range(3)): print(i) 打印结果: (0, 0) (1, 1) (2, 2)
7.合并两个List的方法
l1 = [1, 2, 3] l2 = [4, 5, 6] l1.extend(l2) # 把l2的元素放入l1中 l1 + l2 # 生成一个新的列表,包含l1和l2的元素
未完待续...