파이썬 리스트 오름차순 정렬
조회수 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]
을 넣으면 첫번째 원소에 대해 오름차순 정렬을 해줍니다.-
(•́ ✖ •̀)
알 수 없는 사용자
-
댓글 입력