我被要求计算用户输入的字符串中字母、空格和标点符号的出现次数,并且在打印输出中,字母应按照它们在文本中出现的顺序出现,但任何字母都不应出现两次,而且小写和大写应该算作一个。到目前为止我的代码看起来像这样。
S = str(input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
for char in S:
if char in alpha:
count = S.count(char)
print(char,':',count)
输出
Enter a string: hello
h : 1
e : 1
l : 2
l : 2
o : 1
我希望它看起来像这样
Enter a string: hello
h : 1
e : 1
l : 2
o : 1
我在想是否将字符串和出现的字符的计数转换成像这样的嵌套列表
Enter a string: hello
[['h', 1], ['e', 1], ['l', 2], ['l', 2], ['o', 1]]
我可以删除相同的列表并只留下一个吗?
>>> s = 'hello'
>>> s = s.lower()
>>> print('\n'.join('{} : {}'.format(c, s.count(c)) for i, c in enumerate(s) if c in "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! " and c not in s[:i]))
h : 1
e : 1
l : 2
o : 1
这是使用
Counter
模块的 collections
的经典情况:
from collections import Counter
S ='hello'
S = S.lower()
d = Counter(S)
for item, ct in d.items():
print '%s occured %d times' % (item, ct)
只需迭代
set
S = str(input("Enter a string: ")).lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
for char in set(S):
if char in alpha:
print(char,':',S.count(char))
你可以这样做:
S = 'hello'
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
seen=set()
for c in S:
if c not in seen and c in alpha:
print '{} : {}'.format(c, S.count(c))
seen.add(c)
打印:
h : 1
e : 1
l : 2
o : 1
所以我想出了如何在不使用集合和计数器的情况下做到这一点。
S = (input("Enter a string: "))
S = S.lower()
alpha = "abcdefghijklmnopqrstuvwxyz!@#$%^&*()! "
L = []
#counts the occurrence of characters in a string.
#then puts them in a list
for char in S:
if char in alpha:
count = S.count(char)
L.append(char)
L.append(count)
#turns list into a nested list
L2 = []
i = 0
while i <len(L):
L2.append(L[i:i+2])
i += 2
#checks that the lists dont appear more than once
L3 = []
for i in L2:
if i not in L3:
L3.append(i)
# print out the letters and count of the letter
for i,k in L3:
print(i,k)
可能很长,但它有效。想听听您的意见吗?
这应该是问题的最佳解决方案
#打印字符串中每个字符出现的次数,包括空格和标点符号
text = "India won the ODI worldcup in the year 2011 !"
counter = dict()
for word in text:
for char in word:
count = text.count(char)
counter[char] = count
print(counter)
字典排除了冗余键,并为我们提供了每个字符出现的单个键。