我正在努力制作各种各样的口袋妖怪“数据库”。我希望程序输出每个小宠物:名称,类型,演变,演变为。每个名称都是我pokemon
字典中的一个键。每个值都是另一个字典,其中包含作为键的信息(类型,演变,演变为)。这些键值是理想的输出。问题是type
键有一个列表作为其值,当我尝试运行它时出现此错误:
Name: Bulbasaur
Traceback (most recent call last):
File "pokemon.py", line 51, in <module>
print("Type: " + info["type"])
TypeError: cannot concatenate 'str' and 'list' objects
以下是我的代码:
pokemon = {
"bulbasaur": {
"type": ["grass", "poison"],
"evo_from": "none",
"evo_to": "ivysaur"
},
"ivysaur": {
"type": ["grass", "poison"],
"evo_from": "bulbasaur",
"evo_to": "venusaur"
},
"venusaur": {
"type": ["grass", "poison"],
"evo_from": "ivysaur",
"evo_to": "none"
},
"charmander": {
"type": ["fire"],
"evo_from": "none",
"evo_to": "charmeleon"
},
"charmeleon": {
"type": ["fire"],
"evo_from": "charmander",
"evo_to": "charizard"
},
"charizard": {
"type": ["fire", "flying"],
"evo_from": "charmeleon",
"evo_to": "none"
},
"squirtle": {
"type": ["water"],
"evo_from": "none",
"evo_to": "wartortle"
},
"wartortle": {
"type": ["water"],
"evo_from": "squirtle",
"evo_to": "blastoise"
},
"blastoise": {
"type": ["water"],
"evo_from": "wartortle",
"evo_to": "none"
}
}
for poke, info in pokemon.items():
print("\nName: " + poke.title())
print("Type: " + info["type"])
print("Evolves from " + info["evo_from"])
print("Evolves to " + info["evo_to"])
我希望输出看起来像这样:
Name: Bulbasaur
Type: Grass, Poison
Evolves from none
Evolves to Ivysaur
答案 0 :(得分:3)
您的type
dict成员是一个列表,您无法连接字符串和列表。而是将列表中的所有成员连接到一个字符串中并显示该字符串。
print("Type: " + ', '.join(info["type"]))
或者如果您希望以通常的repl格式显示列表
print("Type: %r" % info["type"])
答案 1 :(得分:3)
实际上,如果不将后者转换为字符串,则无法连接字符串和列表。
幸运的是,对于print
,您不需要连接。您可以单独打印这两个项目:
print("Type:", info["type"])
这将使用列表的默认Python表示。如果您想自定义此选项,可以使用str.join
:
print("Type:", ", ".join(info["type"]))
答案 2 :(得分:1)
type是一个列表,您需要将其视为这样,您需要决定如何使用字符串显示列表元素,
首先,您可能希望以逗号分隔
"Type: {}".format(','.join(info["type"]))
答案 3 :(得分:1)
问题是您有types
作为列表。您想使用str.join()
:
for poke, info in pokemon.items():
print("\nName: " + poke.title())
print("Type: " + ', '.join(info["type"]))
print("Evolves from " + info["evo_from"])
print("Evolves to " + info["evo_to"])
答案 4 :(得分:0)
只需更改此行:
print("Type: " + info["type"])
到此:
print("Type: " + str(info["type"]))