Python列表函数生成1个额外列表

时间:2015-12-14 18:37:43

标签: python list python-2.7

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','电','正常'],
          ['Golem','80','120','Rock','Fighting'] ] ]

强括号是额外的,我无法找到哪一行产生额外的列表。

2 个答案:

答案 0 :(得分: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]]

然后,您使用+并将追加这些列表连接到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模块已经打开并为您读取文件,您不需要自己打开文件。

答案 1 :(得分:0)

在追加方法中添加列表时,您正在创建列表列表,然后将其附加到列表中。