繁体   English   中英

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

[英]how to sort it in order of the input

我需要编写一个代码,其中代码计算输入中相似字母的数量。 但是,输出应与输入顺序相同。 例如,如果输入中有“ 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))
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

您可以将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列表检查是否已显示任何字母。

>>> 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)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM