【问题标题】:Iterating from a dictionary with proper print formatting从具有正确打印格式的字典中迭代
【发布时间】:2021-06-23 03:09:47
【问题描述】:

我有这本字典,我需要将其以表格的方式格式化为文本文件。

dictionary_lines = {'1-2': (69.18217255912117, 182.95794152905918), '2-3': (35.825144800822954, 175.40503498180715), '3-4': (37.34332738254673, 97.30771061242511), '4-5': (57.026590289091914, 97.33437880141743), '5-6': (57.23912298419586, 14.32271997820363), '6-7': (55.61382561917492, 351.4794228420951), '7-8': (41.21551406933976, 275.1365340619268), '8-1': (57.83213034291623, 272.6560961904868)}

到目前为止,我正在先将它们打印出来,然后再编写新文件。我坚持如何正确格式化它们。到目前为止,这是我得到的:

for item in dictionary_lines:
    print ("{l}\t{d:<10.3f}\t{a:<10.3f}".format(l= ,d =,a = ))

我希望它像这样打印:

Lines[tab] Distances [tab]  Azimuth from the South
Key 0       value1 in tuple0  Value2 in tuple0

【问题讨论】:

  • 你听说过熊猫吗?我认为这在这里会有所帮助。您可以从字典中创建 pandas DataFrame。它有一个 .from_dict() 方法。然后你可以打印你的数据框并得到一个很好的输出。
  • 好的,那么......究竟是什么阻止了你完成“你到目前为止所得到的”?它的哪一部分你不知道该怎么做,或者是什么让你感到困惑?请阅读How to Ask,然后提出一个实际问题
  • @chrisaramar 我没听说过。我会调查的。

标签: python list dictionary file-handling


【解决方案1】:

您没有使用format() 中字典中的数据。

另外,考虑使用items() 来迭代字典的键值对:

for key, value in dictionary_lines.items():
    print ("l={}\td={:<10.3f}\ta={:<10.3f}".format(key, value[0], value[1]))

l=1-2   d=69.182        a=182.958   
l=2-3   d=35.825        a=175.405   
l=3-4   d=37.343        a=97.308    
l=4-5   d=57.027        a=97.334    
l=5-6   d=57.239        a=14.323    
l=6-7   d=55.614        a=351.479   
l=7-8   d=41.216        a=275.137   
l=8-1   d=57.832        a=272.656  

【讨论】:

  • 是的,我想,在format() 命令中使用字典会出错。谢谢你!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
相关资源
最近更新 更多