[('d', 100), ('c', 99), ('a', 89), ('b', 86)]如何快速得出['d','c','a','b']
arr1 = [('d', 100), ('c', 99), ('a', 89), ('b', 86)]
arr2 = []
for key in range(len(arr)):
arr2.append(arr[key][0])
感觉好low,有什么好的办法吗?
其实在用Python中在刷leetcode来学习
题目:https://leetcode.com/problems/top-k-frequent-elements/
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
items = {}
for item in nums:
if items.has_key(item):
items[item]+=1
else:
items[item]=1
arr1 = sorted(items.iteritems(), key=lambda asd:asd[1], reverse=True)
arr2 = []
for key in range(len(arr1)):
arr2.append(arr1[key][0])
return arr2[0:k]
怪我咯2017-04-17 17:45:28
매우 간단합니다. 목록 이해를 사용하세요.
으아악귀하의 원래 질문을 보고 간결한 버전으로 작성했습니다. 참고하시면 됩니다.
(Python2.7+, Python3에 적용 가능)
사용 :
으아악효과:
으아악설명:
Python 2.7 이상 버전의 경우 collections
라이브러리에 Counter
클래스가 있습니다.
자세한 조작 방법은 카운터 객체를 참고하세요
Counter(lst)
을 사용하면 Counter
의 요소를 이미 계산한 lst
인스턴스를 쉽게 얻을 수 있습니다.
이후에는 most_common(k)
메서드를 사용하여 정렬된 튜플 목록을 쉽게 얻을 수 있으며, 발생 빈도가 가장 높은 항목만 남습니다. 마지막으로 list comprehension
을 사용하여 요소 자체를 제거합니다. >
으아악