python - 显示更改表单字典
问题描述
我有一个文本文件如下:
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 中可读,就像在文本文件中一样。预先感谢您的慷慨帮助。:)
解决方案
@jasonharper 和 @joshmeranda 已经回答了这个问题。本质上,此代码将按照您的意愿格式化您的文本:
for plantname, details in list(plants.items()):
print(f"{plantname}'s info is:\n" + '\n'.join(details), "\n")
推荐阅读
- javascript - 在新窗口中打开页面时使用 JavaScript 时如何隐藏地址栏
- react-native - react-native 中 @react-navigation/bottom-tabs 中的双阴影颜色显示
- java - 如何在 Spring Boot 项目中获取 connectTimeout 值?
- r - x 使用 mutate 时二进制运算符的非数字参数
- linux - 使用 VNC 远程访问 KVM Instance
- python - 熊猫索引列
- oop - 究竟什么是抽象?
- nginx - nginx反向代理重写自定义标头(不是URL)
- json - 在 postgresql 中对 json 数组进行排序
- java - 在没有指定 POJO 的杰克逊图书馆中排序