sorted 함수를 사용해 python dictionary를 정렬할 수 있다. [방법1] lambda 표현식 사용 dict_a = {'a': 1, 'b': 2, 'c': 3} print(sorted(dict_a.items(), key=lambda x: x[1], reverse=True)) [('c', 3), ('b', 2), ('a', 1)] [방법2] itemgetter 함수 사용 from operator import itemgetter dict_a = {'a': 1, 'b': 2, 'c': 3} print(sorted(dict_a.items(), key=itemgetter(1), reverse=True)) [('c', 3), ('b', 2), ('a', 1)]
sort 함수와 sorted 함수를 사용할 수 있다. key로는 lambda 표현식과 itemgetter 함수를 사용할 수 있다. [방법1] list의 sort 함수 사용하기 (lambda 표현식) list_a = [('a', 1), ('b', 2), ('c', 3)] list_a.sort(key=lambda x: x[1], reverse=True) print(list_a) [('c', 3), ('b', 2), ('a', 1)] ※ sort 함수는 list 자체를 정렬시킨다. [방법2] sorted 함수 사용하기 (itemgetter 함수) from operator import itemgetter list_a = [('a', 1), ('b', 2), ('c', 3)] list_result = sorted..
Counter 클래스와 list의 count 함수를 사용할 수 있다. dictionary를 정렬하기 위해 items 함수를 사용해 tuple로 구성된 list를 생성하면 좋다. [방법1] collections.Counter 클래스 사용 from collections import Counter list_a = ['a', 'b', 'b', 'c', 'c', 'c'] count_a = Counter(list_a) print(count_a) print(count_a.items()) Counter({'c': 3, 'b': 2, 'a': 1}) dict_items([('a', 1), ('b', 2), ('c', 3)]) ※ Counter 클래스에 dictionary도 사용할 수 있다. [방법2] list count..
list 함수의 파라미터는 1개이다. >>> help(list) class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items list 변수에 여러 개의 list 데이터를 할당하기 위해서는 list 함수 안에 1개의 리스트를 입력해야 한다. list1 = ['a', 'b', 'c'] list2 = ['d', 'e', 'f'] lists = list([list1, list2]) print(lists) [['a', 'b', 'c'], ['d', 'e', 'f']]
- Total
- Today
- Yesterday