【问题标题】:Python - 'function' object is not iterable for a high scores tablePython - '函数'对象对于高分表是不可迭代的
【发布时间】:2013-12-02 18:00:35
【问题描述】:

我正在尝试创建一个高分表,以相反的顺序列出游戏的高分,并保留前十名。我将它们定义为 2 个函数

我有 2 个问题,

1 - 每次我尝试运行 display_scores 部分时都会收到此错误:

'function' object is not iterable

2 - 当我添加多个分数时,每个分数都会被替换而不是添加到列表中。例如:得分为 8 的 Jim 将在添加另一个分数时被替换。

我可能在这里做一些愚蠢的事情,但我还在学习!

我的代码:

def display_scores():

    print("\n     High Scores\n")
    print("Name", "\t\tScore")
    print("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
    for entry in scores:
        name, score = entry
        print(name, "\t\t", score)




def scores():
    """The High Scores Table."""


    scores = []

    name = input("What is your name?")
    score = score_counter
    entry = (name, score)
    scores.append(entry)
    scores.sort(reverse=True)
    scores = scores[:10]

    print("\n     High Scores\n")
    print("Name", "\t\tScore")
    print("¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯")
    print(name, "\t\t", score)

【问题讨论】:

  • 修正缩进。如果缩进被破坏,我们无法判断您的代码的结构。
  • 分数方法和分数数组的名称相同

标签: list function object iterable defined


【解决方案1】:

你必须 1)更改函数的名称和 2) 使分数全球化

scores = []

def display_scores():
    print("\n     High Scores\n")
    print("Name", "\t\tScore")
    print("------------------")
    for entry in scores:
        name, score = entry
        print(name, "\t\t", score)



def scores1():
    """The High Scores Table."""

    global scores 
    name = input("What is your name?")
    score = score_counter
    entry = (name, score)
    scores.append(entry)
    scores.sort(reverse=True)
    scores = scores[:10]

    print("\n     High Scores\n")
    print("Name", "\t\tScore")
    print("--------------")
    print(name, "\t\t", score)

【讨论】:

  • 这解决了我的迭代问题,但是我的分数仍然没有正确附加,它们被替换了,但是感谢您解决了我的显示问题!
  • 我检查了它附加的代码是否正确..我附加了三个记录,然后使用 display_scores 显示所有条目..
猜你喜欢
  • 2014-04-26
  • 2018-04-30
  • 1970-01-01
  • 2015-07-09
  • 2013-06-18
  • 2015-09-29
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多