测试你的Python 水平----3

本文深入探讨了Python编程中的常见问题及解决方案,包括列表、元组、字典的区别与联系,else语句的不同应用场景,不使用中间变量进行变量交换的方法,计算阶乘的简洁方式,以及两种实现单例模式的具体代码示例。

1、问:简述python中列表、元组、字典的异同?

答:列表和元组都是任意对象的有序集合,通过偏移量存取,而字典是无序的映射,通过键值对存取,他们都支持嵌套。同时列表是元素和长度可变,而元组是不可变的。

2、问:简述python中else语句的用法?
答:
1)if-else语句:if条件值不满足时执行else语句中内容。
2)while/for-else语句:while循环完成后执行else语句,但是会被break跳过。
3)try-else语句:程序未检测出异常的时候执行。

3、第三题

定义:

a=5
b=6
请实现a和b值的交换,要求不能使用任何中间1变量?
答:(a,b)=(b,a)

4、问:编写程序计算10!。
答:比较简洁的实现方法:
f=lambda x,y:x*y
reduce(f,range(1,11))

5、问:使用python实现一个单例模式。

答:1)


import threading

class Singleton(object):

instance=None

mutex=threading.Lock()


@staticmethod

def getInstance():

if None==Singleton.instance:

Singleton.mutex.require()

if None==Singleton.instance:

Singleton.instance=Singleton()

Singleton.mutex.release()


return Singleton.instance


2)

def singleton(cls, *args, **kw):    

instances = {}    

def _singleton(*args,**kw):    

if cls not in instances:    

instances[cls] = cls(*args, **kw)    

return instances[cls]    

return _singleton


@singleton

class Singleton(object):

pass


转载于:https://my.oschina.net/jastme/blog/506682

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值