programing

내림차순으로 Python 목록 정렬

goodjava 2022. 12. 30. 17:12

내림차순으로 Python 목록 정렬

이 목록을 내림차순으로 정렬하려면 어떻게 해야 하나요?

timestamps = [
    "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"
]

그러면 배열의 정렬된 버전이 나타납니다.

sorted(timestamps, reverse=True)

인플레이스 정렬을 원하는 경우:

timestamps.sort(reverse=True)

Sorting HOW TO에서 문서를 확인합니다.

한 줄에서,lambda:

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

함수의 전달list.sort:

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

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

간단하게 다음과 같이 할 수 있습니다.

timestamps.sort(reverse=True)

단순 유형:

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

고객님의 리스트는 이미 오름차순으로 되어 있기 때문에, 간단하게 리스트를 되돌릴 수 있습니다.

>>> timestamps.reverse()
>>> timestamps
['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']

여기 다른 방법이 있다


timestamps.sort()
timestamps.reverse()
print(timestamps)

언급URL : https://stackoverflow.com/questions/4183506/python-list-sort-in-descending-order