基于元素的属性对列表的元素进行分组

2024-05-13 13:06:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下清单

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)将List的这些元素分组在一起,对于那些为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]进一步划分它们

感谢您的帮助。你知道吗


Tags: listr2r1g4cfsg1g2fcl
3条回答

这里是一个使用dict的答案,其中键是索引[1](ex-'CFS'),其值是另一个dict,其中键是索引[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])

因此,当您打印排序的\u值时,您会得到:

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

如果这是一个一次性的任务列表,那么理解可能是最简单的解决方案:

>>> 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')]]

我会做一个自定义排序例程:

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]]

相关问题 更多 >