2017-06-28 8 views
0

私はこの値の表を持っており、どのようにプログラムに各行を読み込ませることができるのだろうと思っていました。 'a'、 'g'、 'c'、または 'u'を含む行ごとに、カウントを1つ増やしたいとします。リストがない、どういうわけかスクリプトが行を読み込む際にカウントを増やす方法は?

rna_residues = ['a','c','g','u'] 
count_dict = {} 
     #Making the starting number 0 
     rna_count = 0 
     #if any lines of the file starts with one of the rna_residue 
     if line.startswith(tuple(rna_residues)): 
      for residue in line: 
       if residue in rna_residues: 
        rna_count += 1 
      count_dict[line] = [rna_count] 
      print count_dict  

、私はそれを実行すると:この例では、私はそれを実行すると、それは私が試したコードは以下の通りです12.

a 1 0.000 S 
g 2 0.260 S 
a 3 0.990 S 
a 4 0.980 S 
c 5 0.000 S 
u 6 1.000 S 
c 7 0.000 S 
a 8 1.000 S 
a 9 1.000 T 
u 10 0.820 S 
a 11 1.000 T 
g 12 0.000 S 
F 13 1.000 S 
S 14 1.000 S 
T 15 1.000 S 

の結果を持っている必要がありますカウントの:

{'a 1 0.000 S\n': [1]} 
{'g 2 0.260 S\n': [1]} 
{'a 3 0.990 S\n': [1]} 
{'a 4 0.980 S\n': [1]} 
{'c 5 0.000 S\n': [1]} 
{'u 6 1.000 S\n': [1]} 
{'c 7 0.000 S\n': [1]} 
{'a 8 1.000 S\n': [1]} 
{'a 9 1.000 T\n': [1]} 
{'u 10 0.820 S\n': [1]} 
{'a 11 1.000 T\n': [1]} 
{'g 12 0.000 S\n': [1]} 

私はこれは多くの情報ですが、これで私を助けることができるヒントはありますか?どうもありがとう!!

答えて

1

すべての行を辞書のキーとして使用しているため、同じ行がない限り、すべての値は1になります。なぜ辞書が必要なのですか? 'a','c','g','u'のいずれかの文字で始まる行の数を数えたいと思っていました。このため

、次のコードで十分である。

rna_residues = ['a','c','g','u'] 
rna_count = 0 
with open('/path/to/file') as opened_file:  
    for line in opened_file: 
     # or if line[0] in rna_residues 
     if any(line.startswith(residue) for residue in rna_residues): 
      rna_count += 1 
print rna_count 
# 12 
関連する問題