Python Snippets

1. 版本号比较

# -*- coding: utf-8 -*-

import re


def compare_version(v1, v2):
    """比较两个版本的大小
    :parm v1: string. eg. 1.0.0
    :parm v2: string
    """
    ver1 = re.split('\.', v1) 
    ver2 = re.split('\.', v2) 

    ver1 = [int(ver1[i]) for i in range(len(ver1))]
    ver2 = [int(ver2[i]) for i in range(len(ver2))]

    if (ver1 > ver2):
        return 1
    if (ver1 < ver2):
        return -1
    if (ver1 == ver2):
        return 0


v1 = '1.4.9'
v2 = '1.5.0'

if compare_version(v1, v2) < 0:
    print '%s < %s' % (v1, v2)

2. 计算年龄

from datetime import datetime, date

today = date.today()
born = datetime.strptime('19900101', '%Y%m%d')
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))

3. 已知序列的元素,按指定元素的顺序排序

a = [ 
    ('A', 301, 'tsetA'),
    ('B', 302, 'testB'),
    ('C', 301, 'testC'),
    ('A', 303, 'testD'),
    ('B', 302, 'testB'),
]

cs = (302, 301, 303)

d = {k: v for v, k in enumerate(cs)}

print sorted(a, key=lambda n: d.get(n[1]))
# [('B', 302, 'testB'), ('B', 302, 'testB'), ('A', 301, 'tsetA'), ('C', 301, 'testC'), ('A', 303, 'testD')]

4. 分割列表

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

5. 动态加载模块

# python 3.5+
import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

# python 3.3~3.4
from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

# python 2
import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

6. 解三(多)元一次方程

# x + 2y + z = 7
# 2x - y + 3z = 7
# 3x + y + 2z = 18

import numpy as np

a = [[1, 2, 1], [2, -1, 3], [3, 1, 2]]
a = np.array(a)

b = [7, 7, 18]
b = np.array(b)

x = np.linalg.solve(a, b)
array([ 7.,  1., -2.])

7. 全局变量

class Singleton(type):

    def __init__(self, name, bases, dic):
        super(Singleton, self).__init__(name, bases, dic)
        self.instance = None

    def __call__(self, *args, **kwagrs):
        if self.instance is None:
            self.instance = super(Singleton, self).__call__(*args, **kwagrs)
        return self.instance


class GlobalObject:

    __metaclass__ = Singleton

    def __init__(self):
        self.name = None

8. 初始defaultdict数值

from collections import defaultdict

a = defaultdict(lambda: [0, 0.0])
a['test'][0] += 5