반응형

단어 리스트 단어길이순, 단어순 정렬하기


txt = 'but soft what light in yonder window breaks'

words = txt.split()

t = list()

for word in words:

   t.append((len(word), word))


t.sort(reverse=True)


res = list()

for length, word in t:

    res.append(word)


print res



단어를 리스트에 담을때 길이도 같이 담는다. 


.sort() 는 첫번째 요소를 정렬하고 첫번째 요소가 동일하면 두번째 요소를 정렬한다. 


reverse=True 는 내림차순(큰것에서 작은것)으로 정렬해준다. 


 * 파일에 저장하기

with open( "./단어장파일.txt", "w", encoding='utf-8' ) as file_con:

    for length, word in t:

        file_con.append(word)


        


...

반응형
반응형

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