2015-12-14 57 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方法添加的列表。