You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Python字典查询结果的垂直输出?

问题解决:实现动物名称垂直输出

你的代码核心问题是字典里的动物没有用列表包裹,Python会自动把相邻的字符串字面量拼接成一个长串,比如"cow""sheep"会直接变成"cowsheep",所以输出时是连在一起的单行内容。

按下面的步骤修改即可实现垂直输出:

1. 修正字典结构

把每个分类下的动物改成列表形式,让每个动物成为独立元素:

animaldictionary={
    "house pets": ["cat", "dog", "bird", "hamster", "snake"],
    "farm animals": ["cow", "sheep", "chicken", "goat", "pig"]
}

2. 实现垂直输出的两种方法

方法一:用for循环逐个打印

获取分类后遍历列表,每个动物单独打印:

category = input('enter the category:')
for animal in animaldictionary[category]:
    print(animal)

方法二:用换行符拼接后打印

用'\n'.join()把列表元素拼接成带换行的字符串,一次性打印:

category = input('enter the category:')
print('\n'.join(animaldictionary[category]))

两种方法都能实现你要的垂直输出效果,比如输入farm animals后,输出:

cow
sheep
chicken
goat
pig

内容的提问来源于stack exchange,提问作者31913謝名旭

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:15:36