파이썬 리스트 오름차순 정렬

조회수 1046회
file = open("C:/temp/data.txt","r")

words = (word for line in file for word in line.split())

counts = dict()
for word in words:
    counts[word] = counts.get(word,0) + 1
tmp = [(k,v) for (k),(v) in counts.items()]
print(tmp)

입력하면

[('it', 10), ('was', 10), ('the', 10), ('best', 1), ('of', 9), ('times', 2), ('worst', 1), ('age', 2), ('wisdom', 1), ('foolishness', 1), ('epoch', 2), ('belief', 1), ('fo', 1), ('incredulity', 1), ('season', 2), ('light', 1), ('darkness', 1), ('spring', 1), ('hope', 1), ('winter', 1), ('despair', 1)] 

`` 이렇게 출력됩니다

이걸 오름차순으로 정렬하려면 어떻게 하면 되나요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • file = open("C:/temp/data.txt","r")
    
    words = (word for line in file for word in line.split())
    
    counts = dict()
    for word in words:
        counts[word] = counts.get(word,0) + 1
    tmp = sorted([(k,v) for k, v in counts.items()], key=lambda x: x[0])
    print(tmp)
    

    sorted함수 key인자에 lambda x: x[0]을 넣으면 첫번째 원소에 대해 오름차순 정렬을 해줍니다.

    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)