我在比较不同大小的列表时遇到了Python中的一个问题。 正如标题所提到的,我有一个降价报告文件的标题列表。 行的排列方式应确保每列与其对应的标题相匹配
我从一个结构如下的文件中读取记录:
|Filename=timer|Description=Signal Timer|OnBootSec=5min|Unit=some.service|WantedBy=some.target|
|Filename=activator|Description=activator timer|OnBootSec=3min|OnUnitActiveSec=1hr|Unit=some.service|WantedBy=some.target|WantedBy=some.target|
|Filename=mode|Description=mode timer|OnBootSec=4min|Unit=some.service|WantedBy=some.target|
|Filename=reset|Description=reset timer|After=some.service|PartOf=some.service|OnActiveSec=1min|Unit=sometime.service|WantedBy=some.target|
我阅读了这个文件,并准备使用降价格式。 我为它编写的代码缺少一些要点。然而,我想与大家分享
report = open (output,"w+")
for i in range(0,len(titles)):
report.write(titles[i]+"|")
report.write("\n")
report.close
for i in range(0,len(titles)):
report.write("|------")
report.write("|\n")
report.close
for i in range(0,len(titles)):
if (titles[i]==aList[i][1][0]):
report.write(aList[i][1][0] +'='+ aList[i][1][1])
else:
report.write("|")
report.close
在最后一个for循环中格式化之后,我尝试比较并在它们之间添加额外的“|”,以便创建一个没有元素的字段
除此之外,它还有这样的结构:
[0, ['WantedBy', 'some.target|\n']]
基本上,第一个元素是组号,具有相同组号的每条记录将写入同一行。第二个元素集包括一个键/值对。这就是为什么我在它们之间加上“=”号
所需的降价输出是一个表:
|Filename|Description|OnBootSec|Unit|WantedBy|OnUnitActiveSec|After|PartOf|
|------|------|------|------|------|------|------|------|
|Filename=timer|Description=Signal Timer|OnBootSec=5min|Unit=some.service|WantedBy=some.target|
|Filename=activator|Description=activator timer|OnBootSec=3min|Unit=some.service|WantedBy=some.target WantedBy=some.target|OnUnitActiveSec=1hr|||
|Filename=mode|Description=mode timer|OnBootSec=4min|Unit=some.service|WantedBy=some.target|
|Filename=reset|Description=reset timer|OnActiveSec=1min|Unit=sometime.service|WantedBy=some.target||After=some.service|PartOf=some.service|
我感谢你的时间和反馈
问候
另外,您可能需要检查http://dillinger.io/上的输出
你的问题的简单答案似乎是:使用字典
让我们首先重写一些现有代码,使其更具python风格和可读性。最上面几行是示例数据,我已将报告文件重置为仅打印到标准输出,但除此之外,我认为这更易于使用:
你会注意到我把它转换成了字典。根据你的评论,已经有一本包含这些值的字典,所以我认为你可以去掉中间人
我没有麻烦打印字段名,因为列的标题已经包含了该信息
相关问题 更多 >
编程相关推荐