python - 我想使用 sum 函数来计算特定字符的多次出现,但我的脚本只适用于一个字符
问题描述
这个脚本应该计算蛋白质的总重量,所以我决定计算脚本中某些字符的出现次数。然而,只有第一个等式产生的结果导致总重量为相同的值(第一个下的所有值都为零,这绝对是不正确的)。如何让我的脚本关注其他行???这是一个缩短的版本:
akt3_file = open('AKT3 fasta.txt', 'r') #open up the fasta file
for line in akt3_file:
ala =(sum(line.count('A') for line in akt3_file)*89*1000) #this value is 1780000
arg =(sum(line.count('R') for line in akt3_file)*174*1000)
asn =(sum(line.count('N') for line in akt3_file)*132*1000)
asp =(sum(line.count('D') for line in akt3_file)*133*1000)
asx =(sum(line.count('B') for line in akt3_file)*133*1000)
protein_weight = ala+arg+asn+asp+asx
print(protein_weight) # the problem is that this value is also 1780000
akt3_file.close() #close the fasta file
解决方案
您遇到的问题是您尝试多次迭代文件的行。虽然这实际上是可能的(与大多数迭代器不同,文件对象可以用 倒带seek
),但您没有正确执行此操作,因此除了第一次之外的所有迭代都看不到任何数据。
在这种情况下,您可能根本不需要遍历这些行。只需将文件的全文读入一个字符串,然后从该字符串中计算出您想要的字符:
with open('AKT3 fasta.txt', 'r') as akt_3file: # A with is not necessary, but a good idea.
data = akt_3file.read() # Read the whole file into the data string.
ala = data.count('A') * 89 * 1000 # Now we can count all the occurrences in all lines at
arg = data.count('R') * 174 * 1000 # once, and there's no issue iterating the file, since
asn = data.count('N') * 132 * 1000 # we're not dealing with the file any more, just the
asp = data.count('D') * 133 * 1000 # immutable data string.
asx = data.count('B') * 133 * 1000
推荐阅读
- python - 高斯混合模型 (GMM) 提供与训练数据无关的结果
- c++ - 只允许使用静态数据成员模板
- flutter - 需要查询或条件才能在颤动中获取选定的数据
- pysimplegui - PySimpleGUI 和 PySimpleGUIQt 中的菜单行为
- c - 为什么它说它需要是可修改的,它需要是一个常数
- ocaml - 如何接收从函子构建的类型作为 OCaml 中函数的参数?
- fft - 使用 FFT 为 Shamir Secret Share 加速 Berlekamp Welch 算法
- docker - 在 gitlab ci 作业中使用 kubectl 创建 ImagePullSecret 时出现奇怪的错误
- python - 期权价格路径的 Python 蒙特卡罗模拟
- java - HttpServletResponse 的 sendRedirect 调用无法执行