如何按输入顺序对其进行排序

时间:2015-03-27 03:50:46

标签: python count

我需要编写一个代码,其中代码计算输入中相似的字母数。但是输出应该与输入的顺序相同。例如,如果" Hello World"在输入中输出应该说 H:1 e:1 l:3 o:2  :1 W:1 r:1 d:1

到目前为止,我有这个

import collections
sentence = input ('Enter a sentence : ')

#using Counter to count all the letters
letter_counts = collections.Counter(sentence)

#using sort to arrange the words in order.
for letter, count in sorted(letter_counts.items()):
   print(letter, ':', str(count))

3 个答案:

答案 0 :(得分:1)

string = "Hello World"

for index, char in enumerate(string):
    if char not in string[:index]:
        print '{0}: {1}'.format(char, string.count(char))

输出:

H: 1
e: 1
l: 3
o: 2
 : 1
W: 1
r: 1
d: 1

答案 1 :(得分:0)

您可以将for循环更改为以下内容:

unique_letters = []

#using sort to arrange the words in order.
for letter in sentence:
    if letter not in unique_letters and letter is not ' ':
        print(letter + ': ' + str(letter_counts[letter]), end=' ')
        unique_letters.append(letter)    

结果是:

H: 1 e: 1 l: 3 o: 2 W: 1 r: 1 d: 1 

在代码中,我遍历原始句子,并使用unique_letters列表检查是否已经显示任何字母。

答案 2 :(得分:0)

>>> from collections import OrderedDict
>>> sentence = 'Hello World'
>>> count = OrderedDict((word, sentence.count(word)) for word in sentence)
>>> print count
OrderedDict([('H', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('W', 1), ('r', 1), ('d', 1)])