【问题标题】:Using Counters and Lists in Python?在 Python 中使用计数器和列表?
【发布时间】:2013-08-14 13:26:29
【问题描述】:

这是我的程序:

msg = input("What is your message? ")

print ()

num_alpha = 26
int_array = [0] * num_alpha

for alpha in range(num_alpha):
    int_array[alpha] = chr(alpha + 65)
    print(int_array[alpha], end = "")

print()

lett = 0
otherch = 0
num_vowels = 0
num_consanants = 0

count_character = [0] * 100000

length = len(msg)

for character in msg.upper():
    if character == "!":
        print("lett =", lett)
        print("other char = ", otherch)
        print("num_vowels = ", num_vowels)
        print("num_consanants = ", num_consanants)
    elif character < "A" or letter > "Z":
        otherch = otherch + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        print(count_character[ord(character)])
    else:
        lett = lett + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        print(count_character[ord(character)])

for character in msg:
        print("character", character, "appeared" , count_character[ord(character)] , "times")

我的意思是列出有关消息的各种功能(每个字母出现的次数、元音的数量、非字母字符的数量等),但每次我打印最后一个打印语句时,它都会声明每个角色出现 0 次。 有帮手吗?

编辑:我已经想通了 -

因为之前的循环,而不是:

for character in msg:
    print("character", character, "appeared" , count_character[ord(character)] , "times")

代码需要是:

for character in msg.upper():
    print("character", character, "appeared" , count_character[ord(character)] , "times")

【问题讨论】:

  • 如果出现“!”,则应该停止阅读该消息出现
  • 看起来你在计算它们时使用了大写字符,但最后你打印出可能是小写字符的计数(你没有在第二个中使用 msg.upper() for 循环)。

标签: python arrays list character counter


【解决方案1】:

我认为或至少一个问题是,如果您使用 input() 而不是 raw_input(),则需要小心

方法 input() 被认为是未保存的,而 raw_input 真正读入一个字符串/字符

>>> input()
a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 1, in <module>
NameError: name 'a' is not defined
>>> raw_input()
a
'a'
>>>

另请注意:

>>> input()
"hello my name is tom"
'hello my name is tom'
>>> raw_input()
"hello my name is tom"
'"hello my name is tom"'
>>>

raw_input() 始终将输入识别为字符串,而您必须输入引号才能让 input() 知道您要输入字符串

【讨论】:

  • 他正在使用 print 函数,这意味着 Python 3,它没有 input/raw_input 问题。
  • 啊好吧...对不起。但是在 python 2.7 中也可以使用 print
猜你喜欢
  • 1970-01-01
  • 2015-07-12
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多