programing

Python 사전의 고유 키 수 계산

javaba 2022. 11. 5. 11:26
반응형

Python 사전의 고유 키 수 계산

키워드 반복에 대한 사전 매핑 키워드를 가지고 있지만, 다른 단어 목록만 원하기 때문에 키워드 수를 세고 싶었습니다.키워드 수를 셀 수 있는 방법이 있나요, 아니면 다른 단어를 찾을 수 있는 방법이 있나요?

len(yourdict.keys())

아니면 그냥

len(yourdict)

파일에서 고유한 단어를 세고 싶다면 다음과 같이 사용할 수 있습니다.

len(set(open(yourdictfile).read().split()))

구별되는 단어의 수(즉, 사전의 항목 수)는 다음을 사용하여 찾을 수 있습니다.len()기능.

> a = {'foo':42, 'bar':69}
> len(a)
2

모든 개별 단어(즉, 키)를 가져오려면.keys()방법.

> list(a.keys())
['foo', 'bar']

부르기len()사전에서 직접 작업할 수 있으며 반복기를 만드는 것보다 더 빠릅니다.d.keys(), 및 콜len()하지만 그 속도는 당신의 프로그램이 하고 있는 다른 어떤 것과 비교해도 무시할 수 있을 것입니다.

d = {x: x**2 for x in range(1000)}

len(d)
# 1000

len(d.keys())
# 1000

%timeit len(d)
# 41.9 ns ± 0.244 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

%timeit len(d.keys())
# 83.3 ns ± 0.41 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

키워드 수를 세는 질문이라면 다음과 같은 것을 추천합니다.

def countoccurrences(store, value):
    try:
        store[value] = store[value] + 1
    except KeyError as e:
        store[value] = 1
    return

주요 함수에는 데이터를 루프하여 값을 카운트 오카렌스 함수에 전달하는 무언가가 있다.

if __name__ == "__main__":
    store = {}
    list = ('a', 'a', 'b', 'c', 'c')
    for data in list:
        countoccurrences(store, data)
    for k, v in store.iteritems():
        print "Key " + k + " has occurred "  + str(v) + " times"

코드 출력

Key a has occurred 2 times
Key c has occurred 2 times
Key b has occurred 1 times

투고된 답변 UnderWaterKremlin에서 python3 프루프를 만들기 위해 몇 가지 수정이 이루어졌습니다.아래의 놀라운 결과입니다.

시스템 사양:

  • python = 3.7.4,
  • conda = 4.8.0
  • 3.6Ghz, 8코어, 16GB
import timeit

d = {x: x**2 for x in range(1000)}
#print (d)
print (len(d))
# 1000

print (len(d.keys()))
# 1000

print (timeit.timeit('len({x: x**2 for x in range(1000)})', number=100000))        # 1

print (timeit.timeit('len({x: x**2 for x in range(1000)}.keys())', number=100000)) # 2

결과:

1) = 37.0100378

2) = 37.002148899999995

그래서 그런 것 같아요.len(d.keys())현재 사용 속도보다 빠릅니다.len().

사전의 키워드 수를 카운트하려면 다음 절차를 수행합니다.

def dict_finder(dict_finders):
    x=input("Enter the thing you want to find: ")
    if x in dict_finders:
        print("Element found")
    else:
        print("Nothing found:")

언급URL : https://stackoverflow.com/questions/2212433/counting-the-number-of-distinct-keys-in-a-dictionary-in-python

반응형