简体   繁体   English

如何对复杂的 Python 列表进行排序?

[英]How can I sort a complex Python list?

I have a complex list of events and times that I want to sort.我有一个复杂的事件和时间列表,我想对其进行排序。 I want to have the events listed by the start time, so an event on April 1st goes before an event on April 2nd.我想按开始时间列出活动,因此 4 月 1 日的活动先于 4 月 2 日的活动。

The problem is, is that the events are sorted in a (weird?) list that looks like this:问题是,事件是在一个(奇怪的?)列表中排序的,如下所示:

all_events = [['My Event', 1588766400], 
              ['Cinco de Mayo', 1588636800], 
              ["Mother's Day", 1589068800], 
              ['Memorial Day', 1590364800], 
              ["Father's Day", 1592697600], 
              ['Independence Day observed', 1593734400], 
              ['Independence Day', 1593820800], 
              ['Tax Day', 1594771200], 
              ['Labor Day', 1599436800], 
              ['Columbus Day (regional holiday)', 1602460800], 
              ['Halloween', 1604102400]]

If you convert the epochs to RFC 2822, you can see the Cinco de Mayo is supposed to go first, then My Event.如果将纪元转换为 RFC 2822,您可以看到 Cinco de Mayo 应该首先是 go,然后是我的事件。 (I used https://coderstoolbox.net/unixtimestamp/ ) (我用的是 https://coderstoolbox.net/unixtimestamp/

I would have taken the times from all_events to another list by doing我会通过这样做将时间从all_events带到另一个列表

times = []

for event in all_events:
    times.append(event[1])

and then sort them using the Python sorted() function but then if I sort just the times, I wouldn't be able to keep track of the differences the the times list.然后使用 Python sorted() function 对它们进行排序,但是如果我只对时间进行排序,我将无法跟踪times列表的差异。

So is there a way to keep track of the differences in a list and apply the differences to another list?那么有没有办法跟踪列表中的差异并将差异应用于另一个列表? (Whoa, that was a mouthful) (哇,那是一口)

Just sort by the time:只需按时间排序:

sorted(all_events, key=lambda event: event[1])

or if you want to make it more verbose/explicit/well-typed:或者如果你想让它更详细/明确/键入良好:

from typing import List, Union

Event = List[Union[int, str]]  # [name: str, time: int]

def get_event_time(event: Event) -> int:
    assert isinstance(event[1], int)
    return event[1]

sorted(all_events, key=get_event_time)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM