나는 카운터가 main_dict = Counter()
으로 선언되었고 값은 main_dict[word] += 1
으로 추가되었습니다. 결국 나는 15 이하의 모든 원소를 제거하고자합니다. 이 작업을 수행하려면 Counters
에 어떤 기능이 있습니까?카운터에서 임계 값보다 적은 수의 오브젝트를 제거합니다.
도움을 주시면 감사하겠습니다.
나는 카운터가 main_dict = Counter()
으로 선언되었고 값은 main_dict[word] += 1
으로 추가되었습니다. 결국 나는 15 이하의 모든 원소를 제거하고자합니다. 이 작업을 수행하려면 Counters
에 어떤 기능이 있습니까?카운터에서 임계 값보다 적은 수의 오브젝트를 제거합니다.
도움을 주시면 감사하겠습니다.
아니요, 수동으로 제거해야합니다. itertools.dropwhile()
를 사용하게 좀 더 쉽게 아마도 그 :
from itertools import dropwhile
for key, count in dropwhile(lambda key_count: key_count[1] >= 15, main_dict.most_common()):
del main_dict[key]
데모 :
만 카운트가 15 이상되는 키를 테스트 할 필요가dropwhile
를 사용하여
>>> main_dict
Counter({'baz': 20, 'bar': 15, 'foo': 10})
>>> for key, count in dropwhile(lambda key_count: key_count[1] >= 15, main_dict.most_common()):
... del main_dict[key]
...
>>> main_dict
Counter({'baz': 20, 'bar': 15})
; 그 후에는 테스트를 거치지 않고 모든 것을 통과해야합니다. 정렬 된 most_common()
목록과 잘 맞습니다. 15 이하의 값이 많으면 모든 테스트의 실행 시간이 절약됩니다.
또 다른 방법 :
c = Counter({'baz': 20, 'bar': 15, 'foo': 10})
print Counter(el for el in c.elements() if c[el] >= 15)
# Counter({'baz': 20, 'bar': 15})
>>> main_dict = Counter({'apple': 20, 'orange': 14, 'mango': 26, 'banana': 12})
>>> for k in list(main_dict):
if main_dict[k] < 15:
del main_dict[k]
>>> main_dict
Counter({'mango': 26, 'apple': 20})
는 내가 같은 문제가
또한from collections import Counter
main_dict = Counter({'baz': 20, 'bar': 15, 'foo': 10})
trsh = 15
main_dict = Counter(dict(filter(lambda x: x[1] >= trsh, main_dict.items())))
print(main_dict)
>>> Counter({'baz': 20, 'bar': 15})
다른 솔루션을 제안 할 수 있습니다,하지만 난 값으로 카운터에서 모든 키의 목록을 반환해야 어떤 한계점 이상. 주파수는 사실이 생각에서 작동 할 수 이하 15 이상이기 때문에이
keys_list = map(lambda x: x[0], filter(lambda x: x[1] >= trsh, main_dict.items()))
print(keys_list)
>>> ['baz', 'bar']
을 위해 나는 – jamylak
는 또한'bar''가 삭제되어서는 안된다이 경우에 dropwhile''의 지점을 볼 수 없습니다 키를 삭제하는 것과는 다른 방법입니다. 예. 'new_dict = dict (takewhile (lambda x : x [1]> = 15, main_dict.most_common()))' – jamylak
@jamylak :'dropwhile'는 일치를 멈 추면 테스트를 중단합니다. 차이를 만드는 많은 수의 키가 필요합니다. 나중에 오류를 조사하겠습니다. –