【发布时间】:2013-01-30 18:48:52
【问题描述】:
尝试分析 2 列(颜色 number_of_occurances).tsv 文件,该文件的标题行带有字典。尝试以最通用的方式跳过标题行(假设这是通过要求第二列是 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 Observedgreen 15gold 20green 35
【问题讨论】:
-
查看输入文件的样本会很有帮助...
-
你为什么用
item[2]而不是item[1]?由于在选项卡上拆分tab分隔线只会给出 2 个元素列表。 -
标题总是一行吗?如果是这样,只需将
next(F)放在您的列表理解之前。 (当然,我不确定您是否需要列表理解,因为您似乎所做的只是遍历列表。) -
@RohitJain 对不起,这是一个错字,当我从我的脚本在这里重新输入代码时,编码仍然是相当新的思考“第二”列。 item[1] 是正确的,应该被使用过。
标签: python variables types try-except