生信分析Python编程高级技巧

1. 使用statistics模块进行统计运算

statistics 模块是 Python 标准库的一部分,专门用于执行基本的统计运算

import statistics
import random

random.seed(123)
list_num = [random.randint(1,10) for _ in range(5)]
print(list_num)
# [1, 5, 2, 7, 5]

# 平均数
mean = statistics.mean(list_num)
# 中位数
median = statistics.median(list_num)
# 标准差
std = statistics.variance(list_num)
# 众数
mode = statistics.mode(list_num)

print(f"mean: {mean}")
print(f"median: {median}")
print(f"std: {std}")
print(f"mode: {mode}")

# [1, 5, 2, 7, 5]
# mean: 4
# median: 5
# std: 6
# mode: 5

2. 使用策略模式

将算法实现和使用分开,使得算法变化时不影响其他的代码运行。

实现分为以下三步:

策略接口:定义了所有支持的算法的公共接口;
具体策略:实现了策略接口的具体算法或方法;
上下文:使用策略对象来调用具体算法。

from abc import ABC, abstractmethod

class MappingMethod(ABC):
    """定义策略接口"""
    @abstractmethod
    def mapping(self, method):
        pass
    
class BwaMem(MappingMethod):
    """bwa mem比对具体策略"""
    def mapping(self):
        return "Using bwa mem..."
    
class Bowtie2(MappingMethod):
    """bowtie2比对具体策略"""
    def mapping(self):
        return "Using bowtie2..."
    
class Alignment():
    """上下文类"""
    def __init__(self, method: MappingMethod):
        self._method = method
        
    def set_method(self, method: MappingMethod):
        self._method = method
        
    def run_alignment(self):
        return self._method.mapping()
    
if __name__ == '__main__':
    
    # 比对实例
    alignment = Alignment(BwaMem())
    print(alignment.run_alignment()) 
    
    # 切换为bowtie2比对
    alignment.set_method(Bowtie2())
    print(alignment.run_alignment())
    
	# Using bwa mem...
	# Using bowtie2...

3. 使用字段访问元组

使用字段访问元组, 避免使用索引直接访问元组。

from collections import namedtuple

# 创建namedtuple,包含sample_id和sample_name 2个字段
dtuple = namedtuple('sample_info', ['sample_id', 'sample_name'])

# 实例化dtuple对象
sample_dtuple = dtuple("sample-01", 'test')

# 访问字段
print(sample_dtuple.sample_id)
print(sample_dtuple.sample_name)
# sample-01
# test

4. 使用deque操作队列

deque是一个双端队列,支持从两端添加和删除元素, deque比列表处理队列效率更高。

from collections import deque

# 创建双端队列
queue = deque(['sample1', 'sample2', 'sample3'])
print(queue)

# 左侧添加元素和右侧添加元素
queue.appendleft('sample0')
queue.append('sample4')
print(queue)

# 左侧删除元素和右侧删除元素
queue.popleft()
queue.pop()
print(queue)


# deque(['sample1', 'sample2', 'sample3'])
# deque(['sample0', 'sample1', 'sample2', 'sample3', 'sample4'])
# deque(['sample1', 'sample2', 'sample3'])

5. 使用decimal模块设置计算的精度

from decimal import Decimal, getcontext

# 设置精度
getcontext().prec = 3

a = Decimal('1.21212')
b = Decimal('1.323')

print(a+b)
# 2.54

6. 使用协程实现并行运行

import asyncio
import time
import os 

async def run_fastq_qc(fastq_path: str):
    print( f"Run fastqc, input fastq path: {fastq_path}")
    await asyncio.sleep(1)
    print( f"Finiash fastqc!")

async def run_mapping(fastq_path: str):
    print(f"Run bwa mem mapping, input fastq path: {fastq_path} ")
    await asyncio.sleep(3)
    print(f"Finish bwa mem mapping!") 
    
async def run_async(fastq_path: str):
    await asyncio.gather(run_fastq_qc(fastq_path), run_mapping(fastq_path))

asyncio.run(run_async(fastq_path="/path/sample.fastq"))

其他Python相关文章

生信数据分析高效Python代码

生信开发中的多进程和多线程编程

轻量级TinyDB数据库文件写入和增删改查操作

Python处理生信分析流程配置文件4种方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生信与基因组学

每一份鼓励是我坚持下去动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值