[英]Python: Print the common letter from user input
Is there a better way the write this code. 有没有更好的方法来编写此代码。 While there are no errors it seems that its printing all the letters I typed sorted into a list.
虽然没有错误,但它似乎可以打印我键入的所有字母,并排入一个列表。
I want to print the common letters in a string, even if more than one. 我想将常见字母打印成一个字符串,即使不止一个。
Here is what I Have 这是我所拥有的
mystr = input("Enter a string:")
s = list(mystr)
letter_counter = {}
for word in mystr:
if word in letter_counter:
letter_counter[word] += 1
else:
letter_counter[word] = 1
user_letter = sorted(letter_counter, key = letter_counter.get, reverse = True)
number_1 = user_letter[:2]
print(number_1)
The only way I can print the correct letters is by setting a limit on 我可以打印正确字母的唯一方法是设置一个限制
number_1 = user_letter[:2]
For example if I enter the following: 例如,如果我输入以下内容:
mystr = input("Thomas Jones")
in the code the printed output would be 在代码中,打印输出将是
print(number_1)
[o], [s]
Which is right but if the limit was set to from 2
to 3
正确,但是如果限制设置为
2
到3
number_1 = user_letter[:3]
It will print [o] [s] [a]
there is only one a
it shouldn't be there. 它将打印
[o] [s] [a]
只有一个a
它不应该存在。 I want it so that any amount the of words the user inputs it will show the correct repeated letter without the limiter. 我想要它,以便用户输入的任何单词数量都将显示正确的重复字母而没有限制符。
I'm liberality stuck I have no idea how to correct this 我是自由主义者,我不知道该如何纠正
from collections import Counter
[letter for letter,count in Counter("Thomas Jones").items() if count > 1]
Your code produces 您的代码产生
letter_counter = {'a': 1, ' ': 1, 'e': 1, 'h': 1, 'J': 1, 'm': 1, 'o': 2, 'n': 1, 's': 2, 'T': 1}
user_letter = ['o', 's', 'a', ' ', 'e', 'h', 'J', 'm', 'n', 'T']
which is all correct. 都是正确的。
If you only want the repetitive letters, try 如果只需要重复字母,请尝试
user_letter = [letter for letter in letter_counter if letter_counter[letter] > 1]
or something similar. 或类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.