python tips

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免费学习笔记(深入)”;

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()

登录后复制

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2281643.html

(0)
上一篇 2025年2月27日 18:49:10
下一篇 2025年2月27日 15:41:16

AD推荐 黄金广告位招租... 更多推荐

发表回复

登录后才能评论