【发布时间】:2018-07-12 09:18:38
【问题描述】:
请向我解释下面注释的行:
def readfile(filename):
lines = [line for line in file(filename)]
cols = lines[0].strip().split('\t')[1:] #why [1:] here? what is it doing?
rows = [] #whats the difference between rows = [] and rows = {}
data=[]
for line in lines[1:]: #what lines[1:] is doing?
p=line.strip().split('\t')
rows.append(p[0])
#why we used float below if my file contains only integer numbers?
data.append([float(x) for x in p[1:]])
return rows,cols,data
【问题讨论】:
-
lines[1:]将生成从index 1开始的lines列表的子列表(切片)。你应该知道python中的列表是从index 0开始的 -
rows = []分配给rows一个空列表,而rows = {}分配一个空字典。lines[1:]从lines的第二个元素开始创建子列表。 -
这里有四个不同的问题,如果它不是已经是重复的,那么它就有资格被关闭为“太宽泛”。请参阅stackoverflow.com/help/on-topic 上的指南——每个 SO 问题都应该是关于一个特定网站上尚未提出的编程问题。
标签: python dictionary list-comprehension