如何为python组合两个循环

2024-10-01 22:41:00 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有两个for循环

for pokemon in pokemonList:
    for key in pokemon:
        print(key)
        break

for files in os.walk("./sprites/"):
    for filename in files:
        print(filename)

我正在尝试使用第一个pokemonList.pokemon中的值重命名sprites文件夹中的文件

在Javascript id中,执行如下操作

for(i=0;i<pokemonList.length;i++){loop through both using i here}

但我不确定如何在python中实现这一点。先谢谢你

口袋妖怪列表:

[{'Milcery'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Alcremie'}, {'Falinks'}, {'Pincurchin'}, {'Snom'}, {'Frosmoth'}, {'Stonjourner'}, {'Eiscue'}, {'Eiscue'}, {'Indeedee'}, {'Indeedee'}, {'Morpeko'}, {'Morpeko'}, {'Cufant'}, {'Copperajah'}, {'Dracozolt'}, {'Arctozolt'}, {'Dracovish'}, {'Arctovish'}, {'Duraludon'}, {'Dreepy'}, {'Drakloak'}, {'Dragapult'}, {'Zacian'}, {'Zacian'}, {'Zamazenta'}, {'Zamazenta'}, {'Eternatus'}, {'Eternatus'}]


Tags: keyinforfilesfilenameprintpokemonsprites
3条回答

您也可以使用索引:

for i in range(len(pokemonList)):
    # do whatever you want with the i index

在python中,可以通过使用方括号索引列表并使用len函数获取列表的长度来执行相同的操作:

     for i in range (0, len(pokemonList)):
         print(pokemonList[i])

在python中,列表索引从0开始

如果“口袋妖怪”和“文件”的范围相同,则可以将循环设置为

for pokemon,files in zip(pokemonList, os.walk("./sprites/")):
    print(pokemon, files)
    # do other stuff

相关问题 更多 >

    热门问题