【问题标题】:How do I remove the curly bracket in my output of dictionary and replace with output i prefer?如何删除字典输出中的大括号并替换为我喜欢的输出?
【发布时间】:2021-12-05 17:21:43
【问题描述】:

我的输出以大括号和字典样式出现在一行中,但我希望它以不同的方式格式化。例如:如果输入是"hello i am"

输出:

am : 1
hello : 1 
i : 1

这是我的代码:



def word_count(q):

    i = dict()
 
    j = q.split()

    j.sort()
  
    for word in j:
        if word in i:
            i[word] += 1
        else:
            i[word] = 1

    return i

sent = input( ).lower()

x = word_count(q)

        

【问题讨论】:

  • 输出中的顺序是否重要,或者行的顺序可以是什么?

标签: python python-3.x dictionary type-conversion output


【解决方案1】:

使用collections.Counter,这是字典的子类:

from collections import Counter

sent = input("Please provide the article: \n" ).lower()

counts = Counter(sorted(sent.split()))

输出为字符串:

print('\n'.join(f'{k}: {v}' for k,v in counts.items()))

输出:

am: 1
hello: 1
i: 1

【讨论】:

    【解决方案2】:

    使用 f 字符串:

    def word_count(sent):
        
        i = dict()
        j = sent.split()
        j.sort()
        
        for word in j:
            if word in i:
                i[word] += 1
            else:
                i[word] = 1
        for k in i:
            return f"{k}:{i[k]}"
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多