2015-12-14 55 views
-5
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 

此代码工作正常,但它似乎产生一个额外的列表。输出看起来像这样:Python列表函数生成1个额外列表

[[ [ 'Geodude', '40', '80', '摇滚', '战斗'],
[ '的Raichu', '60', '90' , '电', '正常'],
[ '傀儡', '80', '120', '摇滚', '战斗'] ]]

强劲的括号是多余的和我不能找不到哪一行产生额外的列表。

回答

4

您构建3个列表清单,p1_p1, p1_p2 and p1_p3 ; each is a list containing another list, because you append the result of str.split()`这些。

每一个看起来是这样的:

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

然后,您可以串联这些列表togeher使用+它们添加到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模块已经打开并读取该文件给你,你不需要自己打开该文件。

+0

是啊你对吧谢谢你 –

0

当您创建一个列表的列表,然后是追加到列表中的append方法添加的列表。