반응형

sorted, 문자열 길이로 정렬, 한글 정렬

the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length


the_list.sort(key=lambda item: (-len(item), item))




#########################################


n = ['aaa', 'bbb', 'ccc', 'dddd', 'dddl', 'yyyyy']

for i in reversed(sorted(n, key=len)):
       print i
       
       
for i in sorted(n, key=len, reverse=True):
        print i

 

-Sort your list by alpha order, then by length.

See the following exmple:

>>> coursesList = ["chemistry","physics","mathematics","art"]
>>> sorted(coursesList,key=len)
['art', 'physics', 'chemistry', 'mathematics']
>>> coursesList.append("mopsosa")
>>> sorted(coursesList,key=len)
['art', 'physics', 'mopsosa', 'chemistry', 'mathematics']
>>> coursesList.sort()
>>> sorted(coursesList,key=len)
['art', 'mopsosa', 'physics', 'chemistry', 'mathematics']
반응형
반응형

Python List sort() Method


* 오름차순이 .sort(), 내림차순은 .sort(reverse=True)


Description

The method sort() sorts objects of list, use compare func if given.

Syntax

Following is the syntax for sort() method −

list.sort([func])

Parameters

NA

Return Value

This method does not return any value but reverse the given object from the list.

Example

The following example shows the usage of sort() method.

#!/usr/bin/python

aList = [123, 'xyz', 'zara', 'abc', 'xyz'];

aList.sort();
print "List : ", aList

When we run above program, it produces following result −

List :  [123, 'abc', 'xyz', 'xyz', 'zara']


반응형

+ Recent posts