【问题标题】:Python & Sorting : Sorting Elements in a Complex ArrayPython & 排序:对复杂数组中的元素进行排序
【发布时间】:2019-09-02 00:53:34
【问题描述】:

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

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 中提出了类似的问题,但现在我有了更复杂的数组。

【问题讨论】:

  • 要按日期分组吗?
  • @Rakesh 是的,订单应该是 26.03.2019, 01.04.2019,03.04.2019
  • myComplex.sort(key=lambda x: x[0][0][::-1])

标签: python arrays python-3.x sorting datetime


【解决方案1】:

使用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) 

【讨论】:

    【解决方案2】:

    我会从您的数组中创建一个 pandas 数据框,并将其分组在日期列之后。 然后,您可以将此数据帧转换回“复杂”数组。

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

    代码sn-p:

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

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 1970-01-01
      相关资源
      最近更新 更多