返回首字母大写的字符串
capitalize()
把一个序列中的空字符串删掉
def not_empty(s):
return s and s.strip()
list(filter(not_empty, ['A', '', 'B', None, 'C', ' ']))
处理字典逐项叠加
from functools import reduce
reduce根据函数逐项作用在字符串上,结果参与第二次计算
筛选回文
def is_palindrome(n):
s = str(n)
return len(s) == 1 or s[:len(s) // 2] == s[-(len(s)//2):]
排序算法
python内置的sorted()函数可以对list[]进行排序还可以传入key值自定义排序规则
按绝对值排序
>>>sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
字符串排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])
['Credit', 'Zoo', 'about', 'bob']
大小写忽略字符串排序
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
降序可以传入第三个参数reverse=True
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
L = [(‘Bob’, 75), (‘Adam’, 92), (‘Bart’, 66), (‘Lisa’, 88)]
对列表根据名字排列
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
print(sorted(L,key=by_name))
根据所有子列表下标为0的排序
利用装饰器输出函数执行的时间
import time
def metric(fn):
def warp(*args,**kw):
print("%s is executed %s"%(fn.__name__,time.asctime(time.localtime(time.time()))))
return fn(*args,**kw)
return warp
@metric
def fast(x, y):
time.sleep(0.0012)
print(x + y)
return x + y;
@metric
def slow(x, y, z):
time.sleep(0.1234)
print(x * y * z)
return x * y * z;
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
判断对象是不是函数用types模块中定义的常量
>>> import types
>>> def fn():
... pass
...
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> type(lambda x: x)==types.LambdaType
True
>>> type((x for x in range(10)))==types.GeneratorType
True
判断是不是某种类型用isinstance
获取一个对象多有的方法并用list返回用dir()
直接操作一个对象的属性和状态
>>> class MyObject(object):
... def __init__(self):
... self.x = 9
... def power(self):
... return self.x * self.x
...
>>> obj = MyObject()
>>> hasattr(obj, 'x') # 有属性'x'吗?
True
>>> obj.x
9
>>> hasattr(obj, 'y') # 有属性'y'吗?
False
>>> setattr(obj, 'y', 19) # 设置一个属性'y'
>>> hasattr(obj, 'y') # 有属性'y'吗?
True
>>> getattr(obj, 'y') # 获取属性'y'
19
>>> obj.y # 获取属性'y'
19
可以给实例绑定方法
class Student(object):
pass
s = Student()
def set_age(self, age): # 定义一个函数作为实例方法
self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
s.set_age(25) # 调用实例方法
s.age # 测试结果
#25
给一个实例绑定的方法对另一个实例是不管用的
要给所有的实例绑定就给类绑定方法
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
__slots__可以限定class能添加的属性
class Student(object):
__slots__ = ('name', 'age')
@property类装饰器
class Student(object):
def get_score(self):
return self._score
def set_score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
class Student(object):
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
这两个类是等价的
示例
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
self._width=value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
self._height=value
@property
def resolution(self):
return self._width*self._height
s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print('测试通过!')
else:
print('测试失败!')
时间转换
import datetime
strdate = '2017/3/16'
d = datetime.datetime.strptime(strdate,'%Y/%m/%d')
print(type(d))
print(d)
#<class 'datetime.datetime'>
2017-03-16 00:00:00