首页 > 解决方案 > 显示更改表单字典

问题描述

我有一个文本文件如下:

Monstera Deliciosa
2018-11-03 18:21:26
Tropical/sub-Tropical plant
Leathery leaves, mid to dark green
Moist and well-draining soil
Semi-shade/full shade light requirements
Water only when top 2 inches of soil is dry
Intolerant to root rot
Propagate by cuttings in water

Strelitzia Nicolai (White Birds of Paradise)
2018-11-05 10:12:15
Semi-shade, full sun
Dark green leathery leaves
Like lots of water,but soil cannot be water-logged
Like to be root bound in pot
  

我设法将所有这些数据显示为一种字典形式,其中键为植物名称(例如 {key = Monstera Deliciosa 和 value = 下面的其余信息进入列表}

下面附上我的代码。

import itertools as it

plants = {}
with open('myplants.txt') as f:
    while True:
        try:
            p = next(f).rstrip()
            plants[p] = list(l.rstrip() for l in it.takewhile(lambda line: line != '\n', f))
        except StopIteration:
            break

for plantname, details in list(plants.items()):
    print(f"{plantname}'s info is: {details}")

输出是:

Monstera Deliciosa's info is: ['2018-11-03 18:21:26', 'Tropical/sub-Tropical plant', 'Leathery leaves, mid to dark green', 'Moist and well-draining soil', 'Semi-shade/full shade light requirements', 'Water only when top 2 inches of soil is dry', 'Intolerant to root rot', 'Propagate by cuttings in water']
Strelitzia Nicolai (White Birds of Paradise)'s info is: ['2018-11-05 10:12:15', 'Semi-shade, full sun', 'Dark green leathery leaves', 'Like lots of water,but soil cannot be water-logged', 'Like to be root bound in pot']

有没有办法用上面提到的 For 循环以下面的格式显示它?

Monstera Deliciosa's info is:
['2018-11-03 18:21:26', 
 'Tropical/sub-Tropical plant', 
 'Leathery leaves, mid to dark green', 
 'Moist and well-draining soil', 
 'Semi-shade/full shade light requirements', 
 'Water only when top 2 inches of soil is dry', 
 'Intolerant to root rot', 
 'Propagate by cuttings in water']

Strelitzia Nicolai (White Birds of Paradise)'s info is:
['2018-11-05 10:12:15', 
 'Semi-shade, full sun', 
 'Dark green leathery leaves', 
 'Like lots of water,
  but soil cannot be water-logged', 
 'Like to be root bound in pot']

这意味着我想让文本在 IDE 中可读,就像在文本文件中一样。预先感谢您的慷慨帮助。:)

标签: python

解决方案


@jasonharper 和 @joshmeranda 已经回答了这个问题。本质上,此代码将按照您的意愿格式化您的文本:

for plantname, details in list(plants.items()):
    print(f"{plantname}'s info is:\n" + '\n'.join(details), "\n")

推荐阅读