繁体   English   中英

如何使用逗号和 & 将列表转换为可读格式?

[英]How do I convert a list into readable format with commas and &'s?

我正在为我的项目使用 pypokedex API。 我有一个列表,其中包含特定口袋妖怪的不同能力。 有些口袋妖怪有 1 种能力,而另一些则有更多。 我希望这些能力是正确可读的英语,我可以作为 output 给出。 例如。 根据收到的 API 数据,Psyduck 有 3 种能力。 三技能分别为湿、云九、疾游。 这些打印为[Ability(name='damp', is_hidden=False), Ability(name='cloud-nine', is_hidden=False), Ability(name='swift-swim', is_hidden=True)]我想要只取能力的名称并像普通人一样格式化它。 预期结果:Psyduck 有 3 种能力,即。 潮湿,云九和swift游。 我需要的类型相同,因为每个口袋妖怪可以有 1 或 2 种类型。 如果您有办法获得我的预期结果,请回答问题。 rest的代码供参考:

import pypokedex

def pokedex_func():
try:
    inp_poke_name = input(
        "Please input the Pokémon's name you want to find information about : "
    )
    p = pypokedex.get(name=inp_poke_name)
    poke_name = p.name[0].upper() + p.name[1:]

    # Pokemon Name and Dex
    print("The Pokémon you searched was " + poke_name)
    print("The Pokédex number of " + poke_name + " is " + str(p.dex))

    # Height and Weight
    print(poke_name + " weighs " + str(p.weight / 10) +
          " Kg and has a height of " + str(p.height * 10) + "cm")

    # TODO : Add a way to tell the user the type of pokemon they searched for.
    print(p.types)

    # All the different base_stats
    print(poke_name + " has " + str(p.base_stats.hp) + " health points, " +
          str(p.base_stats.attack) + " attack points, " +
          str(p.base_stats.defense) + " defense points and " +
          str(p.base_stats.speed) + " speed points")

    # TODO : Add a way to tell the user the abilities of pokemon they searched for.
    print(p.abilities)

    # Pokemon Image/Sprite
    print(p.sprites.front['default'])
except:
    print("Pokémon not found")


pokedex_func()

Output 用于 Psyduck:

Please input the Pokémon's name you want to find information about : Psyduck
The Pokémon you searched was Psyduck
The Pokédex number of Psyduck is 54
Psyduck weighs 19.6 Kg and has a height of 80cm
['water']
Psyduck has 50 health points, 52 attack points, 48 defense points and 55 speed points
[Ability(name='damp', is_hidden=False), Ability(name='cloud-nine', is_hidden=False), 
Ability(name='swift-swim', is_hidden=True)]
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/54.png

注意:这稍后将成为使用 Discord.Py 的 discord 机器人。 因此有一个图像链接,我可以直接发送到任何频道,discord 将嵌入图像。 此外,所有这些输出都将是 discord 消息。

假设p.abilities是一个对象数组,您可以遍历它们:

output = ""

for index, ability in enumerate(p.abilities):
    output += ability.name
    
    if index == len(p.abilities)-2:
        output += " and "
    elif index == len(p.abilities)-1:
        pass
    else:
        output += ", "
    
print(output)

它不是最 Pythonic 的,但它简单易懂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM