2017-06-09 50 views
1

我目前正在處理兩個大型csv數字數據文件。一個這樣的csv,我們稱之爲X,完全由測試對象的數字數據組成。 a的列按健康度量進行排列,如(id,v1,v2,v3,v4)。我想利用這個信息,並創建一個列表的列表,每個列表包含IE作爲以這種方式一個人的信息:將使用條件和附加值構建的列表附加到列表的列表

X=[['1','a','b','c','d'], 
    ['1','e','f','g','h'], 
    ['2','i','j','k','l'], 
    ['3','m','n','o','p']] 

listoflists=[ [['1','a','b','c','d'],['1','e','f','g','h']], #first row 
       ['2','i','j','k','l'], #second 
       ['3','m','n','o','p'] ] #third 

(讓我知道如果我要編輯的格式:我想在列表的列表中,我剛剛用完了列表,因此列表列表= [a,b,c],其中a是第一行,b是第二行,c是第三個 我試過了這個問題的後果,但我最大的問題是我不知道在哪裏創建匹配數據的實體列表,然後將其添加到「主列表」。

#create a set that holds the values of the subject ids. 
    ids=list(set([item[0] for item in X])) 
    #create the list of lists i want 
    listolists=[] 
    for value in ids: 
     listolists.append(sublist) 
     for i in range(len(X)) 
      sublist=[]   #I'm not sure where to create sublists of 
            #matching data and append to listolists 
      if value == X[i][0] 
       sublist.append(X[i] 

所有幫助表示讚賞。謝謝。

+1

'IDs'是否保證連續 - 如果是的話 - 你可以使用'itertools.groupby' - 如果沒有 - 你可以使用'collections.defaultdict' ... –

+0

感謝您的回覆!他們在這種情況下!只是在數據不太好的情況下,我正在尋找一種更通用的方法。 – user7351362

+0

不太清楚你的意思是「通用方式」 - '[list(g)for k,g in itertools.groupby(X,lambda L:L [0])]'應該可以工作嗎? –

回答

1

這裏是東西:

X =[ 
    ['1','a','b','c','d'], 
    ['1','e','f','g','h'], 
    ['2','i','j','k','l'], 
    ['3','m','n','o','p'], 
    ] 

numbers = {x[0] for x in X} 

output = [] 

for num in sorted(numbers): 
    new_list = [sub_list for sub_list in X if sub_list[0] == num] 
    output.append(new_list) 

print(output) 

... 


[[['1', 'a', 'b', 'c', 'd'], ['1', 'e', 'f', 'g', 'h']], 
[['2', 'i', 'j', 'k', 'l']], 
[['3', 'm', 'n', 'o', 'p']]] 

如果需要第二個,而不是嵌套像第一榜第三讓我知道

編輯 - 在你的問題中指定確切格式

X =[ 
    ['1','a','b','c','d'], 
    ['1','e','f','g','h'], 
    ['2','i','j','k','l'], 
    ['3','m','n','o','p'], 
    ] 

numbers = {x[0] for x in X} 

output = [] 

for num in sorted(numbers): 
    new_list = [sub_list for sub_list in X if sub_list[0] == num] 
    if len(new_list) > 1: 
     output.append(new_list) 
    else: 
     output.append((new_list)[0]) 

print(output) 
+1

這看起來不錯!非常感謝! – user7351362

+0

沒問題,如果你在海量數據集中使用這個數據集,你可能希望改變理解,以便在數字發生變化時停止理解,直到完成迭代。如果您滿意,請選擇一個最佳答案。乾杯 – Rosh