尝试分析一个 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
似乎应该有更好的方法来处理尝试和异常。
根据要求摘录文件:
观察到的颜色
绿色 15
黄金 20
绿色 35
请您参考如下方法:
你不能通过将列表切片为 [1:] 来跳过列表中的第一个元素,如下所示:
filelist = [line.strip('\n').split('\t') for line in F][1:]
现在,fileList 根本不会包含第一行的元素,即标题行。
或者,正如@StevenRumbalski 在评论中指出的那样,您可以在列表理解 之前简单地执行next(F, None) 以避免复制您的列表,在这样的第一个元素之后:
with open('file1.tsv') as F:
next(F, None)
filelist = [line.strip('\n').split('\t') for line in F]
此外,如果您在这里使用 defaultdict 会更好。
像这样使用它:
from collections import defaultdict
color_dict = defaultdict(int)
这样,您就不必在操作之前检查 key 是否存在。所以,你可以简单地做:
color_dict[item[0]] += int(item[1])
