0

辞書に数字を累積的に追加したいので、辞書のキーが追加されます。

x = ' '
dict = {}
list = []
while x != '':
x = raw_input('Enter line:')
p = x.split(' ')
if x != '':
    list.append(p)
result = sum(list, [])
result = result
num = []
for a in result:
for n in dict:
    p = a.count(a)
    l = a
    if n == l:
        l += l
dict[a] = p
print dict

raw_input('')

入力からの単語とそれらが入力された回数で「dict」を構成したいと思います。ありがとう

4

3 に答える 3

3

Python 2.7 にはcollections.Counter、これを使用して現在の単語の合計を得ることができます。

于 2012-08-12T04:39:26.710 に答える
3

使用Counter:

from collections import Counter
x=raw_input('enter line\n')
if x.strip():
    x=x.split()
    count=Counter(x)
    dic=dict(count)
    print dic
else:
    print 'you entered nothing'

出力:

>>> 
enter line
cat cat spam eggs foo foo bar bar bar foo
{'eggs': 1, 'foo': 3, 'bar': 3, 'cat': 2, 'spam': 1}

を使用せずにCounter(これはお勧めしません)、以下を使用できますsets

dic= {}
x = raw_input('Enter line:')
if x.strip():
    p = x.split()
    for x in set(p):   #set(p) contains only unique elements of p
        dic[x]=p.count(x)
    print dic
else:
    print 'you entered nothing'

出力:

>>> 
Enter line: cat cat spam eggs foo foo bar bar bar foo
{'eggs': 1, 'foo': 3, 'bar': 3, 'cat': 2, 'spam': 1}
于 2012-08-12T04:45:25.727 に答える
2
from collections import Counter

lines = iter(lambda: raw_input('Enter line:'), '') # read until empty line
print Counter(word for line in lines for word in line.split()).most_common()
于 2012-08-12T04:52:36.470 に答える