【问题标题】:Printing dictionary without brackets打印不带括号的字典
【发布时间】:2021-11-16 22:27:45
【问题描述】:

我正在尝试为一个练习编写一个脚本,该脚本允许我对字符串中的字符进行排序并计算出现次数最多的字符,但我似乎无法以字符串的形式打印出结果作为它的一个元组。任何人对我如何做到这一点有任何想法将不胜感激。

import sys

stringInput = (sys.argv[1]).lower()
stringInput = sorted(stringInput)
DictCount = {}
Dictionary = {}


def ListDict(tup, DictStr):
    DictStr = dict(tup)
    return DictStr


for chars in stringInput:
    if chars in Dictionary:
        Dictionary[chars] += 1
    else:
        Dictionary[chars] = 1

ListChar = sorted(Dictionary.items(), reverse=True, key=lambda x: x[1])

Characters = (ListChar[0], ListChar[1], ListChar[2], ListChar[3], ListChar[4])

print(ListDict(Characters, DictCount))

当前输出:

python3 CountPopularChars.py sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS
{'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}

想要的输出:

d:7,s:7,e:6,j:4,w:3

【问题讨论】:

  • 请用当前的实际输出以及您想要的输出更新您的问题。
  • 只是循环和打印项目,而不是尝试打印字典的表示
  • 目前我尝试循环和打印 for i in range(5): print(*ListChar[i], sep=':', end=",") 但是它的输出有一个 , % 结尾
  • btw DictCount 在您的代码中没有任何作用,应该被删除。

标签: python python-3.x python-2.7 dictionary


【解决方案1】:

以这种方式创建您的输出:

output = ','.join(f"{k}:{v}" for k, v in ListChar)
print(output)

输出:

e:17,d:7,a:3,b:1,c:1

【讨论】:

  • 嗯,好的,但你最终会得到一个尾随 ','
  • 对不起使用这个:output = ','.join(f"{char}:{count}" for char, count in ListChar)
  • @hmnFalahi 这不是很好的编辑答案并添加accept anwer
  • 是的,我确实按照你的说法编辑了我的答案@user1740577
  • @hmnFalahi 每个人都可以在修订面板中看到您答案的旧版本
【解决方案2】:

或者只是:

>>> dct = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
>>> ','.join(f'{k}:{v}' for k,v in dct.items())
'd:7,s:7,e:6,j:4,w:3'

【讨论】:

  • 谢谢!这工作在这个格式化的事情上停留了最长时间:)
【解决方案3】:

试试:

yourDict = {'d': 7, 's': 7, 'e': 6, 'j': 4, 'w': 3}
print(','.join("{}:{}".format(k, v) for k, v in yourDict.items()))

输出:

d:7,s:7,e:6,j:4,w:3

【讨论】:

  • 您好,这几乎成功了,但是我得到的输出在 ':' 和计数之间有一个间距。 d: 7, s: 7, e: 6, j: 4, w: 3
  • 编辑删除间距
  • @TerenceChew:这很奇怪。我赞成这个答案正是因为输出完全符合您的要求。
  • 谢谢!不用担心,它帮助我了解了它做得更多的方式
【解决方案4】:

您的代码高度冗余。您可以使用collections.Counter 帮助以更简洁的方式编写它:

from collections import Counter

# Hard coded stringInput for ease in this test
stringInput = 'sdsERwweYxcxeewHJesddsdskjjkjrFGe21DS2145o9003gDDS'.lower()

c = Counter(stringInput)

ListChar = sorted(c.items(), reverse=True, key=lambda x: x[1])

print(','.join(f"{k}:{v}" for k, v in ListChar[:5]))

【讨论】:

    猜你喜欢
    • 2017-02-25
    • 2015-11-14
    • 1970-01-01
    • 2011-10-12
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多