'int'对象不可订阅

时间:2014-01-24 10:59:17

标签: python

因此,每当我尝试使用Point.top()命令时,我都会继续:

 'int' object is not subscriptable

这个代码:

def top():
    datalist = sorted(Point.dPoint.items(), key=lambda x: x[1][0], reverse=True)
    t = 1
    top = []
    for l in datalist:
        top.append(l[0].title()+": "+str(l[1][0])+(" point" if l[1][0] > 1 else " points"))
        if t == 15:
             break
        t+=1
    return top

这是在文件内部及其保存方式:

charles 45
tim 32
bob 67

我不确定为什么这个错误会继续发生。该代码假设获得得分最高的前15名。它会归还:

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

2 个答案:

答案 0 :(得分:1)

您的一个变量是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'>
>>> 

答案 1 :(得分:0)

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

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 

通过这种方式你会找到奇怪的表达方式:

player_point_couple[1][0]
...
points[0]

表示“积分'的第一个元素”......但“积分”是一个数字,里面没有元素!

修改的 只是为了进入pythonic风格:

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