Python排序:对复杂数组中的元素进行排序

2024-04-25 09:13:27 发布

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

我有一个复杂的数组;每个元素都有子元素,每个子元素都有子元素。我的阵法是

myComplex=[[['03.04.2019', 'Jack', '7']], [['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']]]

让我来解释一下这个数组

以'03.04.2019'开头的子元素;['03.04.2019', 'Jack', '7']

以'26.03.2019'开头的子元素;['26.03.2019', 'Micheal', '8']['26.03.2019', 'Smith', '5']

以'01.04.2019'开头的子元素;['01.04.2019', 'Jack', '11']['01.04.2019', 'Michelle', '2']['01.04.2019', 'George', '9']

在上面的myComplex中,如您所见,每个子元素的第一个子元素都是一个日期。我想把这些子元素和它们的日期一起排序。所以当我输入print(myComplex)时,我想要这样的输出

[[['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']], [['03.04.2019', 'Jack', '7']]]

我该怎么做?你能给我一个解决办法吗? 我在here中问了一个类似的问题,但现在我有了更复杂的数组。你知道吗


Tags: 元素here排序数组smithprintjackgeorge
2条回答

使用collections.defaultdict

例如:

from collections import defaultdict

myComplex=[[['03.04.2019', 'Jack', '7']], [['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']]]
result = defaultdict(list) 
for i in myComplex:
    for j in i:
        result[j[0]].append(j)

print(result.values())

输出:

[[['03.04.2019', 'Jack', '7']],
 [['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']],
 [['01.04.2019', 'Jack', '11'],
  ['01.04.2019', 'Michelle', '2'],
  ['01.04.2019', 'George', '9']]]

使用itertools.groupby

例如:

import datetime        
from itertools import groupby, chain

myComplex=[[['03.04.2019', 'Jack', '7']], [['26.03.2019', 'Micheal', '5'], ['26.03.2019', 'Smith', '8']], [['01.04.2019', 'Jack', '11'], ['01.04.2019', 'Michelle', '2'], ['01.04.2019', 'George', '9']]]
data = chain.from_iterable(myComplex)
result = [list(v) for k, v in groupby(sorted(data, key=lambda x: datetime.datetime.strptime(x[0], "%d.%m.%Y")), lambda x: x[0])]
pprint(result) 

我将从数组中创建一个pandas数据帧,并将其分组到date列之后。 然后可以将这个数据帧转换回“复杂”数组。你知道吗

供参考: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html

代码段:

df.groupby("date").apply(set)

相关问题 更多 >