python - 如何在python中填充矩阵

标签 python matrix

我正在尝试编写需要作为矩阵输出的代码,但由于是新手,我没有做对。基本上我想为每列的每个 A、C、G、T 生成一个计数矩阵。我能够为单个列执行此操作,但很难为其他列执行此操作。

输入文件

>Rosalind_1
ATCCAGCT
>Rosalind_2
GGGCAACT
>Rosalind_3
ATGGATCT
>Rosalind_4
AAGCAACC
>Rosalind_5
TTGGAACT
>Rosalind_6
ATGCCATT
>Rosalind_7
ATGGCACT

到目前为止我的代码

fh_in = open("consensus_seq.txt", 'r')

A_count = 0
C_count = 0
G_count = 0
T_count = 0

result = []
for line in fh_in:
    line = line.strip()
    if not line.startswith(">"):
        for nuc in line[0]:
            if nuc == "A":
                A_count += 1
            if nuc == "C":
                C_count += 1
            if nuc == "G":
                G_count += 1
            if nuc == "T":
                T_count += 1
result.append(A_count)
result.append(C_count)
result.append(G_count)
result.append(T_count)
print result

输出

[5, 0, 1, 1]

我想要的实际输出是

A   5 1 0 0 5 5 0 0
C   0 0 1 4 2 0 6 1
G   1 1 6 3 0 1 0 0
T   1 5 0 0 0 1 1 6

感谢任何帮助/提示。

最佳答案

首先列出行,去掉以 > 开头的行。然后您可以zip 将它变成一个列列表。然后你可以列出每个字母的列数。

rows = [line.strip() for line in infile if not line.startswith('>')]
columns = zip(*rows)
for letter in 'ACGT':
    print letter, [column.count(letter) for column in columns]

但是,如果您的文件非常大,这可能会占用大量内存。另一种方法是逐行计算字母。

counts = {letter: [0] * 8 for letter in 'ACGT'}
for line in infile:
    if not line.startswith('>'):
        for i, letter in enumerate(line.strip()):
            counts[letter][i] += 1
for letter, columns in counts.items():
    print letter, columns

您也可以使用 Counter,尤其是当您事先不确定会有多少列时:

from collections import Counter
# ...
counts = Counter()
for line in infile:
    if not line.startswith('>'):
        counts.update(enumerate(line.strip()))

columns = range(max(counts.keys())[0])
for letter in 'ACGT':
    print letter, [counts[column, letter] for column in columns]

关于python - 如何在python中填充矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26770841/

相关文章:

python - Python 中的矩阵加法 - 列表

python - 是否可以从 cfg 文件中读取变量?

c# - 舍入数字 0.1 到 0.10

android - 如何修复 CameraX 旋转支持

python - Django - 遵循外键关系(即 SQL 中的 JOIN)

algorithm - 时间感知社交图 DS/查询

java - 基质填充 block

Python 将父级设置为实例

python - 将字典列表转换为字典

python - Pyinstaller: AttributeError: 模块 'enum' 没有属性 'IntFlag'