Python和排序:按元素在数组中的子元素排序 [英] Python & Sorting : Sorting Elements In Order Their Subelements in an Array
问题描述
我有一个数组,它有4个元素,每个元素都有3个子元素;
I have an array and it has 4 elements and every element has 3 subelements;
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]
如您所见,每个元素的第一个子元素都是日期。我想订购这些元素及其日期。所以当我输入 print(myList)
;
As you see, every elements' first subelement is a date. And I want to order these elements with their dates. So I want that output when I enter print(myList)
;
[['26.03.2019', 'Michelle', '8'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8'], ['03.04.2019', 'Jack', '2']]
我该怎么做?
推荐答案
print(myList)
只会打印您的列表。您不想摆弄。您要做的是在打印前对列表进行排序。例如,例如:
print(myList)
would just print your list. You do not want to fiddle with that. What you want to do is sort your list prior to printing. Like so for example:
import datetime
myList = [['26.03.2019', 'Michelle', '8'], ['03.04.2019', 'Jack', '2'], ['01.04.2019', 'George', '2'], ['02.04.2019', 'Micheal', '8']]
myList.sort(key=lambda sublist: datetime.datetime.strptime(sublist[0], "%d.%m.%Y"))
print(myList) # -> [['26.03.2019', 'Michelle', '8'],
# ['01.04.2019', 'George', '2'],
# ['02.04.2019', 'Micheal', '8'],
# ['03.04.2019', 'Jack', '2']]
请注意,执行 myList.sort(..)
会永久更改您的列表。如果这不是您想要的,则可以创建一个新的使用@Rakesh在他的答案中建议的排序
。
Note that doing myList.sort(..)
permanently changes your list.. If that is not what you want, you can create a new one using sorted
as @Rakesh proposes in his answer.
荣誉:用于日期排序的代码来自此处
Kudos: the code for the sorting of the dates was taken from here
这篇关于Python和排序:按元素在数组中的子元素排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!