【问题标题】:How to print the same iteration twice?如何两次打印相同的迭代?
【发布时间】:2021-10-12 05:39:50
【问题描述】:

提示: 编写一个读取单词列表的程序。然后,程序会输出这些单词及其频率。

例如:如果输入是:

hey hi Mark hi mark

输出是:

hey 1



hi 2

Mark 1

hi 2

mark 1

我的代码:

from collections import Counter
user.input = input().split()
count = counter(user_input)

for key, value in count.items():
    print('{} {}'.format(key, value))

我已经基本解决了这个问题,但由于某种原因,我的输出不会打印出第二个“hi 2”,如上面的问题提示所示。

【问题讨论】:

  • 打印输入中的单词,而不是集合中的单词

标签: python for-loop split counter


【解决方案1】:

您可以使用给定的句子进行迭代:

from collections import Counter
user_input = input().split()
count = Counter(user_input)

for word in user_input:
    print(f'{word} {count[word]}')

输出:

hey 1
hi 2
Mark 1
hi 2
mark 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多