2011-03-29 67 views
1

我有以下列表分組元素

List=[ 
    ('G1', 'CFS', 'FCL', 'R1'), 
    ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9'), 
    ('G4', 'CFS', 'FCL', 'R10'), 
    ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), 
    ('G1', 'CFS', 'FCL', 'R2'), 
    ('G2', 'LOOSEFREIGHT', 'LCL', 'R5'), 
    ] 

現在我想組列表的這個元件首先通過索引[1](即CFS和LOOSEFREIGHT)在一起,並用於那些爲LOOSEFREIGHT分組在一起的元素,我想根據索引[2](即LCL或MIXEDLCL)進一步將它們分成不同的組。

所以基本上我希望他們分爲不同的名單和我的解決辦法應該是形式

New_List=[ 
    [ 
     ('G1', 'CFS', 'FCL', 'R1'), 
     ('G1', 'CFS', 'FCL', 'R2'), 
     ('G4', 'CFS', 'FCL', 'R10') 
    ], 
    [ 
     ('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), 
     ('G2', 'LOOSEFREIGHT', 'LCL', 'R5') 
    ], 
    [ 
     ('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9') 
    ], 
    ] 

我該怎麼辦呢?

我能夠做到將它們分爲基於索引不同的名單[1]但我沒能進一步分化他們基於指數[2]

任何幫助表示讚賞。

回答

0

如果這是一個一次性的任務列表內涵是可能是最簡單的解決方案:

>>> new_list = [] 
>>> new_list.append([i for i in L if i[1] == 'CFS']) # where L is your original list 
>>> new_list.append([i for i in L if i[1] == 'LOOSEFREIGHT' and i[2] == 'LCL']) 
>>> new_list.append([i for i in L if i[1] == 'LOOSEFREIGHT' and i[2] == 'MIXEDLCL']) 
>>> from pprint import pprint as pp 
>>> pp(new_list) 
[[('G1', 'CFS', 'FCL', 'R1'), 
    ('G4', 'CFS', 'FCL', 'R10'), 
    ('G1', 'CFS', 'FCL', 'R2')], 
[('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5')], 
[('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')]] 

如果您需要更一般的情況,在這裏你不一定知道提前數的例子可能的羣體,你可以使用itertools.groupby是這樣的:

import itertools as it 
import operator as op 
new_list = [] 
for k,g in it.groupby(sorted(L, key=op.itemgetter(1,2)), key=op.itemgetter(1,2)): 
    new_list.append(list(g)) 
pp(new_list) 

結果:

[[('G1', 'CFS', 'FCL', 'R1'), 
    ('G4', 'CFS', 'FCL', 'R10'), 
    ('G1', 'CFS', 'FCL', 'R2')], 
[('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5')], 
[('G3', 'LOOSEFREIGHT', 'MIXEDLCL', 'R9')]] 
0

下面是一個使用字典的答案,其中的索引是索引[1](ex-'CFS'),其值是另一個字典,其索引爲索引[2](ex-'FCL')。此示例創建結構,然後使用for循環打印出您所需的排序順序。它比亞當的回答,因爲他是專門爲特定值構建更強:

sorted_values = [] 
d = {} 
for entry in a: 
    d[entry[1]] = { entry[2]: entry } 

for i in sorted(d): 
    for j in sorted(d[i]): 
    sorted_values.append(d[i][j]) 

因此,當你打印sorted_values,您可以:

[[('G1', 'CFS', 'FCL', 'R1'), ('G4', 'CFS', 'FCL', 'R10'), ('G1', 'CFS', 'FCL', 'R2')], [('G2', 'LOOSEFREIGHT', 'LCL', 'R4'), ('G2', 'LOOSEFREIGHT', 'LCL', 'R5')]] 
0

我會做一個自定義的排序過程:

def custom_sort(data): 
    cfs = [] 
    loose_lcl = [] 
    loose_mixed = [] 
    for row in data: 
     if row[1] == 'CFS': 
      cfs.append(row) 
     elif row[1] == 'LOOSEFREIGHT' and row[2] == 'LCL': 
      loose_lcl.append(row) 
     elif row[1] == 'LOOSEFREIGHT' and row[2] == 'MIXEDLCL': 
      loose_mixed.append(row) 
     else: 
      raise ValueError("Unknown data: %r" % (row,)) 
    return [cfs, [loose_lcl, loose_mixed]]