1. enum
Python code
#!/usr/bin/env python # -*- coding:utf-8 -*- def enum(**enums): return type('Enum', (), enums) Gender = enum(MALE=0,FEMALE=1) print Gender.MALE print Gender.FEMALE
2. Check whether the string is a number
Python code
s='123456789' s.isdigit()#return True
3. List intersection
Python code
s=[1,2,3] w=[2,3,4] list(set(s).intersection(w))
4. Two lists Convert to a dict
Python code
dict(zip(a,b))
5, singleton
Python code
def singleton(cls): instances = {} def get_instance(): if cls not in instances: instances[cls] = cls() return instances[cls] return get_instance
The second singleton mode used in tornado IOLoop:
Python code
@staticmethod def instance(): """Returns a global IOLoop instance. Most single-threaded applications have a single, global IOLoop. Use this method instead of passing around IOLoop instances throughout your code. A common pattern for classes that depend on IOLoops is to use a default argument to enable programs with multiple IOLoops but not require the argument for simpler applications:: class MyClass(object): def __init__(self, io_loop=None): self.io_loop = io_loop or IOLoop.instance() """ if not hasattr(IOLoop, "_instance"): with IOLoop._instance_lock: if not hasattr(IOLoop, "_instance"): # New instance after double check IOLoop._instance = IOLoop() return IOLoop._instance
6.list Duplication removal
Python code
{}.fromkeys(list).keys()