“int”对象不是suscriptab

2024-04-26 03:52:59 发布

您现在位置:Python中文网/ 问答频道 /正文

所以每次我尝试使用我的Point.top()命令时,我都会得到:

 'int' object is not subscriptable

代码如下:

^{pr2}$

这是文件的内部以及如何保存:

charles 45
tim 32
bob 67

我不知道为什么这个错误总是发生。这个代码应该得到前15名中得分最高的人。它将返回:

["Bob: 67 points", "Charles: 45 points", "Tim: 32 points"]

Tags: 文件代码命令objectistopnotpoints
2条回答

其中一个变量是int,而你要做的是variable[0],这是用int做不到的。在

Python 3.3.2 (default, Aug 25 2013, 14:58:58) 
[GCC 4.2.1 Compatible FreeBSD Clang 3.1 ((branches/release_31 156863))] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.

>>> a = 42
>>> a[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable
>>> type(a)
<class 'int'>
>>> 

我建议让代码更加明确,例如:

def top():
    player_points_couples = sorted(Point.dPoint.items(), key=lambda player_point_couple: player_point_couple[1][0], reverse=True)
    top_players_number = 1
    top_players = []
    for player, points in player_points_couples :
        top_players.append(player.title()+": "+str(points[0])+(" point" if points[0] > 1 else " points"))
        if top_players_number == 15:
             break
        top_players_number += 1
    return top_players 

这样你会发现奇怪的表达方式:

^{pr2}$

意思是“点”的第一个元素。。。但是'点'是一个数字,里面没有元素!在

编辑 只是为了进入Python的风格:

def top():
    from operator import itemgetter
    player_points_couples = sorted(Point.dPoint.items(), key=itemgetter(1), reverse=True)

    string_template_singular = "%s: %d point"
    string_template_plural = "%s: %d points"
    top_players = []
    for player, points in player_points_couples[:15]:
        string_template = string_template_plural if points > 1 else string_template_singular
        top_players.append(string_template % (player.title(), points))

    return top_players 

相关问题 更多 >