python tips

[b]1、enum[/b]

#!/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


[b]2、检查字符串是否是number[/b]

s='123456789'
s.isdigit()#return True

[b]3、list取交集[/b]

s=[1,2,3]
w=[2,3,4]
list(set(s).intersection(w))

[b]4、两个list转成一个dict[/b]

dict(zip(a,b))


[b]5、singleton[/b]

def singleton(cls):
instances = {}
def get_instance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return get_instance

第二种tornado IOLoop中使用的单例模式:

@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排重

{}.fromkeys(list).keys()


未完待续...

参考资料:
http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-in-python
http://docs.python.org/2/library/stdtypes.html#str.isdigit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值