热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

pythontips

1、enum#!usrbinenvpython#-*-coding:utf-8-*-defenum(**enums):returntype(Enum,(),enums)Genderenum(MALE0,FEMALE1)printGender.MALEprintGender.FEMALE2、检查字符串是否是number...
1、enum

Python代码

#!/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、检查字符串是否是number

Python代码

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


3、list取交集

Python代码

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


4、两个list转成一个dict

Python代码

dict(zip(a,b))



5、singleton

Python代码

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


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

Python代码

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

Python代码

{}.fromkeys(list).keys()

推荐阅读
author-avatar
欣欣然人人宇
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有