2013-11-22 3 views
-2

나는 단어가되는 키로 특정 사전에서 가장 짧은 단어와 가장 긴 단어를 찾으려고합니다. 사전을 정렬 할 때 아래 코드는 그렇게하지 않습니다. 나는 반바지에 "And"를, 롱에는 "Yours"를 얻습니다. 문제가 무엇입니까? 하지 길이사전에서 가장 짧은 단어와 가장 긴 단어를 찾는 방법

freq={'I': 1, 'heaven': 1, 'filled': 1, 'their': 1, 'termed': 1, 'of': 4, 'And': 3, 'parts': 1, 'neer': 1, 'to': 2, 'song': 1, 'poets': 1, 'The': 1, 'a': 2, 'were': 2, 'verse': 1, 'your': 6, 'knows': 1, 'not': 1, 'half': 1, 'number': 1, 'but': 1, 'yours': 1, 'come': 2, 'rage': 1, 'age': 2, 'Though': 1, 'men': 1, 'fresh': 1, 'heavenly': 1, 'say': 1, 'alive': 1, 'truth': 1, 'this': 1, 'If': 2, 'than': 1, 'old': 1, 'believe': 1, 'Which': 1, 'that': 1, 'You': 1, 'faces': 1, 'yet': 1, 'poet': 1, 'in': 4, 'life': 1, 'most': 1, 'earthly': 1, 'will': 1, 'hides': 1, 'my': 3, 'papers': 1, 'is': 1, 'stretched': 1, 'rights': 1, 'eyes': 1, 'it': 3, 'yellowed': 1, 'Such': 1, 'So': 1, 'all': 1, 'lies': 1, 'the': 1, 'an': 1, 'as': 1, 'write': 1, 'child': 1, 'deserts': 1, 'shows': 1, 'tongue': 1, 'twice': 1, 'Be': 1, 'high': 1, 'some': 1, 'could': 1, 'should': 2, 'and': 2, 'touched': 1, 'like': 1, 'would': 1, 'Who': 1, 'tomb': 1, 'numbers': 1, 'antique': 1, 'scorned': 1, 'metre': 1, 'time': 2, 'touches': 1, 'be': 1, 'with': 2, 'true': 1, 'beauty': 1, 'rhyme': 1, 'less': 1, 'But': 1, 'graces': 1, 'live': 1} 

답변

5

당신은 전적으로 (즉 순) 열쇠를 정렬됩니다

def build_report(freq): 
    report={} 
    #for shorts: 
    sorted(freq.keys()) 
    print(sorted(freq.keys())) 
    shortest=sorted(freq.keys())[0] 
    shorts=list() 
    shorts.append(shortest) 
    print(shorts) 
    report["shorts:"]=shorts 
    #for longs: 
    longest=sorted(freq.keys(),reverse=True)[0] 
    print(sorted(freq.keys(),reverse=True)) 
    longs=list() 
    longs.append(longest) 
    print(longs) 
    report["longs:"]=longs 

내가 입력있어 주파수이다.

너무 자주 정렬하는 중입니다. 정렬 한 번만, 길이 :

keys = sorted(freq, key=len) 
shortest, longest = keys[0], keys[-1] 

이상 반복 사전은 단지 키를 생성하기 때문에, 당신도 여기 .keys()를 호출 할 필요가 없습니다.

데모 :

>>> keys = sorted(freq, key=len) 
>>> shortest, longest = keys[0], keys[-1] 
>>> shortest 
'I' 
>>> longest 
'stretched' 

첫 번째로 같은 길이의 모든 단어해야하는 경우 : itertools.groupby() 사용

shortest = [keys[0]] 
for key in keys[1:]: 
    if len(key) == len(shortest[0]): 
     shortest.append(key) 
    else: 
     break 
longest = [keys[-1]] 
for key in reversed(keys[:-1]): 
    if len(key) == len(longest[0]): 
     longest.append(key) 
    else: 
     break 

또는 좀 더 고급 :

from itertools import groupby 
keys = sorted(freq, key=len) 
shortest = list(next(groupby(keys, key=len))[1]) 
longest = list(next(groupby(reversed(keys), key=len))[1]) 
+0

@JonClements을 : 어, 그래, 네, 정말로, 전 완전히였습니다. (감사). –

+0

같은 길이의 가장 짧은 단어를 어떻게 얻을 수 있습니까? for 루프를 사용하고 목록에 넣은 각 키의 길이를 비교해 보았지만 그 중 하나는 작동하지 않았습니다. – user2976821

+0

''(x) == len (가장 짧은)]'키에있는 x에 대한 x는'가장 짧은 단어의 목록이 될 것입니다. – TehTris

관련 문제