🔧
tool
Python基本语法
**变量和数据类型:** ```python # 数字 integer = 42 floating = 3.14159 # 字符串 dna = "ATGCGCTAGCTA" protein = 'MPLK' # 字符串操作 print(len(dna)) # 长度 print(dna[0:3]) # 切片(前3个碱基) print(dna.cou...
📖 定义
变量和数据类型:
# 数字
integer = 42
floating = 3.14159
# 字符串
dna = "ATGCGCTAGCTA"
protein = 'MPLK'
# 字符串操作
print(len(dna)) # 长度
print(dna[0:3]) # 切片(前3个碱基)
print(dna.count("GC")) # 计数
print(dna.replace("T", "U")) # 替换(DNA转RNA)
print(dna.find("ATG")) # 查找子串位置
# 列表(有序可变)
sequences = ["ATCG", "GCTA", "TAGC"]
sequences.append("CGAT") # 添加元素
print(sequences[0]) # 访问
print(len(sequences)) # 长度
# 字典(键值对)
gene_expr = {
"GAPDH": 25.3,
"ACTB": 18.7,
"TP53": 3.2
}
print(gene_expr["GAPDH"]) # 访问
gene_expr["BRCA1"] = 7.5 # 添加
# 元组(有序不可变)
coordinates = (100, 200)
控制流:
# 条件语句
gc_content = 0.55
if gc_content > 0.6:
print("High GC")
elif gc_content > 0.4:
print("Moderate GC")
else:
print("Low GC")
# for循环
for seq in sequences:
gc = (seq.count("G") + seq.count("C")) / len(seq)
print(f"{seq}: GC={gc:.2%}")
# while循环
i = 0
while i < len(sequences):
print(sequences[i])
i += 1
# 列表推导式(Pythonic写法)
gc_values = [(s.count("G") + s.count("C")) / len(s) for s in sequences]
函数:
def calculate_gc_content(sequence):
"""计算DNA序列的GC含量"""
sequence = sequence.upper()
gc_count = sequence.count("G") + sequence.count("C")
return gc_count / len(sequence)
# 调用
gc = calculate_gc_content("ATGCGCTAGCTA")
print(f"GC content: {gc:.2%}")
# 默认参数
def reverse_complement(seq, rna=False):
"""计算反向互补序列"""
complement = {"A": "T", "T": "A", "G": "C", "C": "G",
"a": "t", "t": "a", "g": "c", "c": "g"}
if rna:
complement["A"] = "U"
complement["a"] = "u"
rc = "".join(complement.get(base, base) for base in reversed(seq))
return rc
print(reverse_complement("ATGC")) # GCAT
print(reverse_complement("ATGC", rna=True)) # GCAU
文件操作:
# 读取文件
with open("sequences.fasta", "r") as f:
content = f.read() # 读取全部
lines = f.readlines() # 读取为列表
# 写入文件
with open("output.txt", "w") as f:
f.write("Hello\n")
# 逐行读取(推荐大文件使用)
with open("data.txt", "r") as f:
for line in f:
line = line.strip() # 去除末尾换行符
if line.startswith(">"):
print(f"Header: {line}")