【问题标题】:Print sorted dict (tuple) with new line for each entry为每个条目打印带有新行的排序字典(元组)
【发布时间】:2017-11-21 19:59:47
【问题描述】:

我有这个字典按频率排序import sys from operator import itemgetter

dictionarydata =  {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)}

当我print(dictionarydata) 我想要这样的输出:

to : 4648
a : 4667
and : 6407
of : 6703

我尝试过的所有方法都不起作用。例如,正则表达式似乎不适用于元组;例如

import re 
with open(dictionarydata) as f: 
for line in f: 
for word in re.findall(r'\w+', line): 
print(word)

【问题讨论】:

  • “我尝试过的所有方法都不起作用”。至少向我们展示您尝试过的一件事,我们将从那里开始。
  • 如果x 是你的元组列表,试试这个:print("\n".join(["{} : {}".format(*l) for l in x]))

标签: python sorting dictionary printing


【解决方案1】:

如果你有看起来像你的 set 的元组:

x = {('to', 4648), ('a', 4667), ('and', 6407), ('of', 6703)}

使用\n 将其格式化以加入行,并使用str.format 创建您想要的行:

print("\n".join(["{} : {}".format(*l) for l in x]))

结果:

to : 4648
a : 4667
and : 6407
of : 6703

请注意,由于您输入的是 set,因此无法保证顺序。如果它是listtuple,那就是。

【讨论】:

    【解决方案2】:
    items = [('a', 1), ('b', 2), ('c', 3)]
    for (key, value) in items:
        print(key, ":", value)
    

    这将给出输出:

    a : 1
    b : 2
    c : 3
    

    这也和做的一样:

    for x in items:
        print(x[0], ":", x[1])
    

    例如。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 2020-11-17
      • 2020-12-04
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多