【发布时间】:2017-02-16 13:19:25
【问题描述】:
我在一个文件中有类似以下的数据:
Name, Age, Sex, School, height, weight, id
Joe, 10, M, StThomas, 120, 20, 111
Jim, 9, M, StThomas, 126, 22, 123
Jack, 8, M, StFrancis, 110, 15, 145
Abel, 10, F, StFrancis, 128, 23, 166
实际数据可能是 100 列和一百万行。
我想要做的是按照以下模式创建一个字典:
school_data = {'StThomas': {'weight':[20,22], 'height': [120,126]},
'StFrancis': {'weight':[15,23], 'height': [110,128]} }
我尝试过的事情:
-
试用 1:(在计算方面非常昂贵)
school_names = [] for lines in read_data[1:]: data = lines.split('\t') school_names.append(data[3]) school_names = set(school_names) for lines in read_data[1:]: for school in schools: if school in lines: print lines -
试验 2:
for lines in read_data[1:]: data = lines.split('\t') school_name = data[3] height = data[4] weight = data[5] id = data [6] x[id] = {school_name: (weight, height)}
以上两种是我尝试过但没有更接近解决方案的方法。
【问题讨论】:
-
其他列是什么?它们是否与计算相关,或者您是否希望像处理体重/身高(按学校分组值)一样处理这些额外的列?
标签: python dictionary