Python认为我的列表是一个元组?

时间:2014-03-14 13:47:46

标签: python list python-2.7 attributes tuples

我有一个名为step_segment的列表。它永远不应该是一个元组。

当我按下" 7"在我的main计划中。我明白了:

Traceback (most recent call last):
  File "G:\programming\python\new_globals.py", line 205, in <module>
    main()
  File "G:\programming\python\new_globals.py", line 203, in main
    pick_random(STATS, step_segment, seen, master)
  File "G:\programming\python\new_globals.py", line 125, in pick_random
    step_segment, STATS = take_step(step_segment, STATS)
  File "G:\programming\python\new_globals.py", line 69, in take_step
    step_segment.append(STATS)
AttributeError: 'tuple' object has no attribute 'append'

只有在调用pick_random()时才会出现错误:

def pick_random(STATS, seen, master):
    step_segment = []
    #if len(seen) >= 256:
    #   return seen, master
    while (len(step_segment)) < 128:
        step_segment, STATS = take_step(step_segment, STATS)
        if STATS[5] == "B":     # when there's a battle:
            randy = random.choice([0,1])
            if randy == 1:      # choose randomly between G and B
                step_segment = do_fight(step_segment, STATS)
            else:
                step_segment = do_glitch(step_segment, STATS)
            seen = seen + [STATS[0],STATS[5]]
    #if step_segment not in master:
        master.append(step_segment)
    time = get_frames(step_segment)
    print seen
    print time
    #return pick_random(STATS, seen, master)
    return seen, master

完整来源:http://pastebin.com/fZgqtxZn

1 个答案:

答案 0 :(得分:4)

do_flight()返回2元组:

return step_segment, STATS

您无法解压缩:

step_segment = do_fight(step_segment, STATS)

在此之后,step_segment成为一个元组。

你可能打算写

step_segment, STATS = do_fight(step_segment, STATS)

作为一般建议,您可能希望保持方法签名的一致性,以避免此类错误和/或学习一些面向对象的编程,这样您就不必继续传递相同的变量无处不在。