Python180道面试题 [49:70] 操作

操作类题目

49.Python 交换两个变量的值

a, b = b, a

50.在读文件操作的时候会使用 read、readline 或者 readlines,简述它们各自的作用

read:读取整个文件。
readline:读取下一行,使用生成器方法。
readlines:读取整个文件到一个迭代器以供我们遍历

51.json 序列化时,可以处理的数据类型有哪些?如何定制支持 datetime 类型?

  • json序列化时,可以处理列表、字典、字符、数值、布尔和None

52.json 序列化时,默认遇到中文会转换成 unicode,如果想要保留中文怎么办?

import json
dict_demo = {"name": "旭东"}
# 使用dumps的默认参数ensure_ascii=True
print(json.dumps(dict_demo, ensure_ascii=False)

53.有两个磁盘文件 A 和 B,各存放一行字母,要求把这两个文件中的信息合并(按字母顺序排列),输出到一个新文件 C 中。

def read_file(file_name):
	with open(file_name, "r") as f:
		return f.read()
		
def write_file(file_name, file_data):
	with open(file_name, "w") as f:
		f.write(file_data)
def letter_sort(letter_str, reverse_flag=False):
	return "".join(sorted(letter_str, reverse=reverse_flag))

if __name__ == '__main__':
	data_1 = read_file("test1.txt")
	data_2 = read_file("test2.txt")
	new_data = letter_sort(data_1 + data_2)
	write_file("new.txt", new_data)

54.如果当前的日期为 20190530,要求写一个函数输出 N 天后的日期,(比如 N 为 2,则输出 20190601)。

from datetime import datetime, timedelta

now_date = datetime.now().strftime("%Y%m%d")
N = 2

# 格式转换
now_date = datetime.strptime(now_date, "%Y%m%d").date()

# 计算偏移
offset_date = timedelta(days=N)
result_day = (now_date + offset_date).strftime("%Y%m%d")

55.写一个函数,接收整数参数 n,返回一个函数,函数的功能是把函数的参数和 n 相乘并把结果返回。

  • 闭包是以一种特殊的函数,由外函数和内函数嵌套组成,外函数返回值是内函数的引用,就构成了闭包;
  • 闭包函数必须返回一个函数对象;
def out_func(n):
	def in_func(num):
		return n*num;
	return in_func

if __name__ == '__main__':
	demo = out_func(3)
	print(demo(4))

# 12

56.下面代码会存在什么问题,如何改进?

57.一行代码输出 1-100 之间的所有偶数。

print([num for num in range(1, 101) if num%2 == 0])

58.with 语句的作用,写一段代码?
with语句:“上下文管理器”,用于资源访问的场合,作用是资源释放和异常处理

import threading

# 来一个用于线程锁的with使用
num = 0  # 全局变量多个线程可以读写,传递数据
thread_lock = threading.lock() # 创建一个锁

class Mythread(threading.Thread):
	def run(self):
		global num
		with thread_lock:				# with Lock的作用相当于自动获取和释放锁(资源)
			for i in range(1000000):	# 锁定期间,其他线程不可以运行
				num += 1
		print(num)				

59.python 字典和 json 字符串相互转化方法

import json
dict_demo = {"a": 1, "b": 2}
# 序列化:使用json.dumps()将python类型转为json字符串
json_demo = json.dumps(dict_demo)
print(type(json_demo))		# <class 'str'>
# 使用json.dump()将python数据序列化到指定文件中
with open("demo.json", "w") as file_obj:
	json.dump(dict_demo, file_obj)

# 反序列化:使用json.loads()将json字符类型转为python类型
dict_demo = json.loads(json_demo)
print(type(dict_demo))		# <class 'dict'>
# 使用json.load()将json字符类型从文件中读出来
with open("demo.json", "r") as file_obj:
	file_data = json.load(file_obj)
	print(file_data)

60.请写一个 Python 逻辑,计算一个文件中的大写字母数量

import re
def capital_count(file_name):
	count = 0
	with open(file_name, "r") as file_obj:
		file_data = file_obj.read()
	file_data = re.sub("[^a-zA-Z]", "", file_data)
	print(file_data)
	for i in file_data:
		if i.isupper():
			count += 1
	return count

if __name__ == '__main__':
	print(capital_count("test.txt"))

61. 请写一段 Python连接 Mongo 数据库,然后的查询代码。
62.说一说 Redis 的基本类型。

string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。

63. 请写一段 Python连接 Redis 数据库的代码。
64. 请写一段 Python 连接 MySQL 数据库的代码。

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost", "testuser", "testpasswd", "TESTDB", charset = 'utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
# 提交修改
cursor.commit()
# 关闭数据库连接
db.close()

65.了解 Redis 的事务么?
66.了解数据库的三范式么?
67.了解分布式锁么?

在开发中可能会用到多线程和多进程,如果不同线程或者不同进程抢占同一个资源,对其行读写操作可能会导致数据不一致,导致数据不是在我们预想的情况下改变。
这里为了保证线程或者进程安全,python中引入了线程锁和进程锁,保证了数据的一致性和完整性。
而为了保证分布式系统的数据安全,可以使用使用分布式锁来解决这一问题(秒杀场景)。
分布式锁其实可以理解为:控制分布式系统有序的去对共享资源进行操作,通过互斥来保持一致性。
分布式锁的实现有很多种,常见的有redis、zookeeper和数据库mysql等。

68.用 Python 实现一个 Reids 的分布式锁的功能。

import time
import redis

class RedisLock(object){
	def __init__(self, key):
		# 连接数据库,创建连接对象
		self.rdcon = redis.Redis(host='', port=6379, password="", db=1)
		# 设置锁的值
        self._lock = 0
        # 分布式锁的键
        self.lock_key = "%s_dynamic_test" % key

	 @staticmethod
	 def get_lock(cls, timeout=10):
	 	"""获取redis分布式锁

        设置分布式锁,判断锁是否超时
        :param cls: 锁的类对象
        :param timeout: 锁超时时间
        :return:
        """
        while cls._lock != 1:
            # 设置锁的过期时间
            timestamp = time.time() + timeout + 1
            # 设置redis分布式锁键值
            cls._lock = cls.rdcon.setnx(cls.lock_key, timestamp)
            # 判断锁的值是否为1,或者当前时间大于锁预期释放的时间,如果成立则退出循环,释放锁
            if cls._lock == 1 or (
            	time.time() > cls.rdcon.get(cls.lock_key) and
            	time.time() > cls.rdcon.getset(cls.lock_key, timestamp)):
            	print("get lock")
                break
            else:
            	time.sleep(0.3)
            	
	@staticmethod
    def release(cls):
    	"""释放锁

        :param cls: 锁的类对象
        :return:
        """
        # 判断当前时间是否大于锁最大释放时间
        if time.time() < cls.rdcon.get(cls.lock_key):
        	print("release lock")
        	cls.rdcon.delete(cls.lock_key)  			        

69.写一段 Python 使用 Mongo 数据库创建索引的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值