2011-03-29 73 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]]