: 빈 문자열이 false로 평가하는 것이
from collections import Counter
words = []
input_word = True
while input_word:
input_word = raw_input()
words.append(input_word)
counted = Counter(words)
for word, freq in counted.items():
print word + " - " + str(freq)
주, 그래서 오히려 빈 같을 때 파괴보다 문자열을 사용하면 문자열을 루프 조건으로 만 사용할 수 있습니다.
편집은 다음 defaultdict
모든 키 0
의 가치가있는 경우를 가리 킵니다 보장
from collections import defaultdict
words = defaultdict(int)
input_word = True
while input_word:
input_word = raw_input()
if input_word:
words[input_word] += 1
for word, freq in words.items():
print word + " - " + str(freq)
: 당신이 학문적으로 Counter
을 사용하지 않으려면, 그 다음 최선의 선택은 collections.defaultdict
입니다 전에 사용 된 적이 없습니다. 이렇게하면 우리가 쉽게 계산할 수 있습니다.
여전히 단어 목록을 유지하려는 경우 추가로해야합니다. 예컨대 :
words = []
words_count = defaultdict(int)
input_word = True
while input_word:
input_word = raw_input()
if input_word:
words.append(input_word)
words_count[input_word] += 1
전체를 읽으면 단어를 계산할 수 있습니다. D : http://docs.python.org/library/collections.html#collections.Counter – jamylak
목적은 카운터를 사용하지 않는 것입니다. – JamieB
아, 그럴 경우 좋습니다. 좋습니다. 'defaultdict'를 사용하는 것이 허용되지 않는 한. – jamylak