辞書付きの見出し行を持つ 2 列 (色 number_of_occurances) の .tsv ファイルを分析しようとしています。可能な最も一般的な方法で見出し行をスキップしようとしています (これは、2 番目の列を int 型にする必要があると仮定します)。以下は私が思いついた最高のものですが、もっと良いものがあるようです:
filelist = []
color_dict = {}
with open('file1.tsv') as F:
filelist = [line.strip('\n').split('\t') for line in F]
for item in filelist:
try: #attempt to add values to existing dictionary entry
x = color_dict[item[0]]
x += int(item[1])
color_dict[item[0]] = x
except: #if color has not been observed yet (KeyError), or if non-convertable string(ValueError) create new entry
try:
color_dict[item[0]] = int(item[1])
except(ValueError): #if item[1] can't convert to int
pass
試行と例外を処理するためのより良い方法があるはずです。
リクエストによるファイルの抜粋:
color Observed
green 15
gold 20
green 35