【问题标题】:Python list function generates 1 extra listPython list 函数生成 1 个额外的列表
【发布时间】:2015-12-14 18:37:43
【问题描述】:
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','摇滚','格斗'],
['Raichu', '60', '90', '电动', '普通'],
['Golem', '80', '120', 'Rock', 'Fighting']]]

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

【问题讨论】:

    标签: python list python-2.7


    【解决方案1】:

    您为这些构建了 3 个列表,p1_p1,p1_p2andp1_p3; each is a list containing another list, because you append the result ofstr.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模块已经为你打开并读取了文件,你不需要自己打开文件。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-08-01
        • 1970-01-01
        • 2011-05-24
        • 2018-04-20
        • 1970-01-01
        • 2018-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多