Python列表按降序排列

本文翻译自:Python list sort in descending order

How can I sort this list in descending order? 如何按降序对列表进行排序?

timestamp = [
    "2010-04-20 10:07:30",
    "2010-04-20 10:07:38",
    "2010-04-20 10:07:52",
    "2010-04-20 10:08:22",
    "2010-04-20 10:08:22",
    "2010-04-20 10:09:46",
    "2010-04-20 10:10:37",
    "2010-04-20 10:10:58",
    "2010-04-20 10:11:50",
    "2010-04-20 10:12:13",
    "2010-04-20 10:12:13",
    "2010-04-20 10:25:38"
]

#1楼

参考:https://stackoom.com/question/HYJu/Python列表按降序排列


#2楼

you simple type: 您简单的输入:

timestamp.sort()
timestamp=timestamp[::-1]

#3楼

This will give you a sorted version of the array. 这将为您提供阵列的排序版本。

sorted(timestamp, reverse=True)

If you want to sort in-place: 如果要就地排序:

timestamp.sort(reverse=True)

#4楼

Since your list is already in ascending order, we can simply reverse the list. 由于您的列表已经按照升序排列,因此我们可以简单地反转列表。

>>> timestamp.reverse()
>>> timestamp
['2010-04-20 10:25:38', 
'2010-04-20 10:12:13', 
'2010-04-20 10:12:13', 
'2010-04-20 10:11:50', 
'2010-04-20 10:10:58', 
'2010-04-20 10:10:37', 
'2010-04-20 10:09:46', 
'2010-04-20 10:08:22',
'2010-04-20 10:08:22', 
'2010-04-20 10:07:52', 
'2010-04-20 10:07:38', 
'2010-04-20 10:07:30']

#5楼

In one line, using a lambda : 在一行中,使用lambda

timestamp.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort : 将函数传递给list.sort

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamp.sort(key=foo, reverse=True)

#6楼

您可以简单地做到这一点:

timestamp.sort(reverse=True)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值