程序重复自身 - 不明白为什么

Program is repeating itself -can't figure out why

到目前为止,这是我的程序...它接受一条消息(来自用户的输入)并告诉用户程序中有多少个 A,多少个 B,等等。除非我输入一条消息,例如 "Dad",它会告诉我有多少 D 有两次,而不是只说一遍。 它说:

D ... 2

一个 ... 1

D ... 2

我想让它说:

一个 ... 1

D ... 2

如何在不使用 zip 且不导入任何内容的情况下解决此问题?

message=input("what is your message?").upper()
alphabet=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
count=[0]*len(alphabet)
for i in message:
    if i in alphabet:
        count[alphabet.index(i)]+=1

for i in message:
    print (i,"...",count[alphabet.index(i)])

(顺便说一句,感谢 Uriel Eli 帮助我获得程序)。

你的第二个 for 循环遍历 message,所以如果用户输入 DAD(好吧......在大写之后),你会得到:

message == DAD
  i = D --> Shows 2
  i = A --> Shows 1
  i = D --> Shows 2 (again)

也许您想要迭代 count,保留您正在迭代的索引(稍后使用它以将其与 alphabet 列表匹配)。类似的东西:

for index, num_occurences in enumerate(count):
    if num_occurences > 0:
        print("Match found at i=%s which corresponds with alphabet[%s]=%s" %
              (index, index, alphabet[index]))
        print(alphabet[index], "...", num_occurences)

你应该检查一下 enumerate 做了什么。

如果你仍然想遍历 message,你可以这样做,使用辅助 set 跟踪你已经显示的字母(这样你就不会显示相同的字母再次)

already_shown_letters = set()
for i in message:
    if i not in already_shown_letters:
        print (i,"...",count[alphabet.index(i)])
        already_shown_letters.add(i)

我不同意你在这里的做法。你实际上把这个复杂化了。解决这个问题的正确方法是实际使用字典来跟踪字符串中的所有字母,并在每次出现相同字符时进行计数。请注意,这也遵循不导入任何内容的规则。

此外,这也消除了拥有要检查的字母列表的必要性。

此外,如果您需要分别计算大小写字符,请不要在输入末尾调用 upper。只需将其删除。如果一定要将大小写算作同一个字符,那你可以不加。

message=input("what is your message?").upper()

d = {}

for c in message:
    if c in d:
        d[c] += 1
    else:
        d[c] = 1

演示

what is your message?thisisastringofthings
{'H': 1, 'F': 0, 'O': 0, 'R': 0, 'G': 1, 'S': 3, 'T': 2, 'A': 0, 'I': 3, 'N': 1}

要提供类似于您期望的输出,您只需遍历最终结果并打印:

对于字符,在d.items()中计算: print("{} ... {}".format(character, count))

最后,只是为了展示 最好的方法,就是实际使用 collections 中的 Counter

>>> from collections import Counter
>>> Counter("thisisastring")
Counter({'s': 3, 'i': 3, 't': 2, 'h': 1, 'n': 1, 'a': 1, 'r': 1, 'g': 1})

仅供将来参考,我知道您现在无法导入任何内容。最好的方法可能是:

from  collections import Counter
message=input("what is your message?").upper()
print(Counter(message))
# Counter({'D': 2, 'A': 1})