簡體   English   中英

如何在python中按照索引和另一個排序列表的順序排列列表?

[英]how to arrange a list in the order of index od another sorted list in python?

我有 2 個清單說,

dates=['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
events=[a,b,c,d,e,f,g,h,i,j]

我按時間順序對列表日期進行了排序,並將值放在列表日期 1 中

dates1=['7/6/2014', '7/10/2014', '7/20/2014', '8/3/2014', '8/11/2014', '9/16/2014', '10/14/2014', '4/21/2015', '4/21/2015', '4/21/2015']

現在如何按照日期 1 的時間順序排列事件?

解決此問題的最簡單方法是將兩個列表zip在一起,然后根據dates數組的日期轉換對它們進行排序。

例子 -

>>> from datetime import datetime
>>> dates=['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
>>> events=['a','b','c','d','e','f','g','h','i','j']
>>> s =  sorted(zip(dates, events), key = lambda x: datetime.strptime(x[0],'%m/%d/%Y'))
>>> s
[('7/6/2014', 'h'), ('7/10/2014', 'd'), ('7/20/2014', 'g'), ('8/3/2014', 'f'), ('8/11/2014', 'e'), ('9/16/2014', 'c'), ('10/14/2014', 'b'), ('4/21/2015', 'a'), ('4/21/2015', 'i'), ('4/21/2015', 'j')]

然后你可以得到使用列表理解排序的事件列表 -

>>> sortedevents = [x[1] for x in s]
>>> sortedevents
['h', 'd', 'g', 'f', 'e', 'c', 'b', 'a', 'i', 'j']

zip函數的作用是將作為參數提供給它的列表(可迭代對象)中相同索引處的元素組合成一個元組列表(第 i 個位置的每個元組包含參數中提供的列表中第 i 個位置的元素的組合)。

這將做到:

sortedevents = sorted(zip(dates, events), key = lambda i: dates1.index(i[0]))

首先我們將日期和事件組合成匹配​​的元組,然后我們使用排序列表dates1對元組進行排序

要自行獲取已排序的事件列表:

events = [e[1] for e in sortedevents]

Anand 的答案可能是首選,因為它不需要單獨排序的日期列表,即不需要日期dates1

另一種方法是使用 numpy 的 argsort 函數,盡管它需要您將事件列表轉換為數組。

import numpy as np
from datetime import datetime

dates = ['4/21/2015', '10/14/2014', '9/16/2014', '7/10/2014', '8/11/2014', '8/3/2014', '7/20/2014', '7/6/2014', '4/21/2015', '4/21/2015']
events = np.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'])

datetimes = [datetime.strptime(date, '%m/%d/%Y') for date in dates]
events_sorted = events[np.argsort(datetimes)]

print(events_sorted)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM