Python list函数生成1个额外的lis

2024-09-28 14:20:31 发布

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

def randomly_pokemon_select_function():
    from random import randint
    import linecache

open_pokedex=open("pokedex.txt","r")

p1_p1=list()
p1_p2=list()
p1_p3=list()
p2_p1=list()
p2_p2=list()
p2_p3=list()
player1_pokemons=list()
player2_pokemons=list()
pokemon_selection=(randint(1,40))
p1_p1.append(linecache.getline("pokedex.txt", pokemon_selection).split())
pokemon_selection=(randint(1,40))
p1_p2.append(linecache.getline("pokedex.txt", pokemon_selection).split())
pokemon_selection=(randint(1,40))
p1_p3.append(linecache.getline("pokedex.txt", pokemon_selection).split())
pokemon_selection=(randint(1,40))
p2_p1.append(linecache.getline("pokedex.txt", pokemon_selection).split())
pokemon_selection=(randint(1,40))
p2_p2.append(linecache.getline("pokedex.txt", pokemon_selection).split())
pokemon_selection=(randint(1,40))
p2_p3.append(linecache.getline("pokedex.txt", pokemon_selection).split())
player1_pokemons.append(p1_p1+p1_p2+p1_p3)
player2_pokemons.append(p2_p1+p2_p2+p2_p3)
open_pokedex.close()
print player1_pokemons
print player2_pokemons
return player1_pokemons,player2_pokemons

这段代码运行良好,但似乎它生成了一个额外的列表。输出如下所示:

[[['Geodude'、'40'、'80'、'Rock'、'Fighting'],
['Raichu'、'60'、'90'、'Electric'、'Normal'],
['Golem'、'80'、'120'、'Rock'、'Fighting']]]

强括号是额外的,我找不到哪一行生成了额外的列表。你知道吗


Tags: txtlistsplitp2randintlinecachep3pokemon
2条回答

您构建了3个列表列表,p1_p1,p1\u p2andp1\u p3; each is a list containing another list, because you append the result of结构拆分()`。你知道吗

每个都是这样的:

[[datum, datum, datum, datum, datum]]

然后使用+将这些列表连接到一起,并将它们附加到已经是列表对象的player1_pokemons。与其附加,不如将其列为您的列表:

player1_pokemons = p1_p1 + p1_p2 + p1_p3

或者不附加到单独的p1_p1p1_p2等列表,而是直接附加到player1_pokemons。您可以在循环中执行此操作:

player1_pokemons = [
    linecache.getline("pokedex.txt", randint(1, 40)).split()
    for _ in range(3)]
player2_pokemons = [
    linecache.getline("pokedex.txt", randint(1, 40)).split()
    for _ in range(3)]

注意,linecache模块已经为您打开并读取文件,您不需要自己打开文件。你知道吗

在append方法中添加列表时,您正在创建一个列表列表,然后将其附加到一个列表中。你知道吗

相关问题 更多 >