2016-04-22 62 views
0

我的目錄的格式如下:我如何劃分列表分爲smallers列表

gymnastics_school,participant_name,all-around_points_earned 

我需要學校把它瓜分,但保持得分。

import collections 

def main(): 
    names = ["gymnastics_school", "participant_name", "all_around_points_earned"] 
    Data = collections.namedtuple("Data", names)  
    data = [] 

    with open('state_meet.txt','r') as f: 
     for line in f: 
      line = line.strip() 
      items = line.split(',') 
      items[2] = float(items[2]) 
      data.append(Data(*items)) 

這些都是它們是如何設置的例子:

Lanier City Gymnastics,Ben W.,55.301 
Lanier City Gymnastics,Alex W.,54.801 
Lanier City Gymnastics,Sky T.,51.2 
Lanier City Gymnastics,William G.,47.3 
Carrollton Boys,Cameron M.,61.6 
Carrollton Boys,Zachary W.,58.7 
Carrollton Boys,Samuel B.,58.6 
La Fayette Boys,Nate S.,63 
La Fayette Boys,Kaden C.,62 
La Fayette Boys,Cohan S.,59.1 
La Fayette Boys,Cooper J.,56.101 
La Fayette Boys,Avi F.,53.401 
La Fayette Boys,Frederic T.,53.201 
Columbus,Noah B.,50.3 
Savannah Metro,Levi B.,52.801 
Savannah Metro,Taylan T.,52 
Savannah Metro,Jacob S.,51.5 
SAAB Gymnastics,Dawson B.,58.1 
SAAB Gymnastics,Dean S.,57.901 
SAAB Gymnastics,William L.,57.101 
SAAB Gymnastics,Lex L.,52.501 
Suwanee Gymnastics,Colin K.,57.3 
Suwanee Gymnastics,Matthew B.,53.201 

處理它應該看起來像後:

Lanier City Gymnastics:participants(4) 

,因爲它自己的名單

Carrollton Boys(3) 

作爲它自己的名單

La Fayette Boys(6) 

+1

如果壓縮列表只是,容參與者算,你怎麼保持得分分別? – Rockybilly

回答

0

我會建議他們將在dictionaries

data = {} 

with open('state_meet.txt','r') as f: 
    for line in f: 
     line = line.strip() 
     items = line.split(',') 
     items[2] = float(items[2]) 
     if items[0] in data: 
      data[items[0]].append(items[1:]) 
     else: 
      data[items[0]] = [items[1:]] 

然後進入學校可以通過以下方式進行:

>>> data['Lanier City Gymnastics'] 
[['Ben W.',55.301],['Alex W.',54.801],['Sky T'.,51.2],['William G.',47.3] 

編輯: 假設您需要整個數據集作爲一個列表,然後再要將其分割成更小的列表中,您可以生成從列表中詞典:

data = [] 

with open('state_meet.txt','r') as f: 
    for line in f: 
     line = line.strip() 
     items = line.split(',') 
     items[2] = float(items[2]) 
     data.append(items) 

#perform median or other operation on your data 

nested_data = {}   
for items in data: 
    if items[0] in data: 
     data[items[0]].append(items[1:]) 
    else: 
     data[items[0]] = [items[1:]] 

    nested_data[item[0]] 

當你需要讓你可以用切片列表的一個子集:

mylist[start:stop:step] 

其中startstopstep是可選的(見link更全面的介紹)

+0

但我必須首先使用清單作爲一個整體來找到平均中位數的第一個和最後一個分數,然後讓他們回到學校,並找到平均每個學校的第一個和最後一箇中位數 –

+0

你是theGOAT非常感謝 –

+0

嘿我得到一個錯誤 –