我试图使用字典来防止自己存储重复项,这很好,但当我试图从字典中取出对象并调用它们上的函数时,解释器告诉我:
Traceback (most recent call last):
File "C:/Users/ejsol/Desktop/NflData/playerDataCollector.py", line 24, in
<module>
print unique_qb[0].stats(2015, week=13)
TypeError: 'OrderedDict' object is not callable
我试着对字典中的元素进行深度复制,并用它们列出清单,但我仍然遇到了同样的问题。我读到了一些关于python如何将名称绑定到对象的信息,这就是为什么我认为从字典中复制对象会起作用,但似乎不起作用。
这是我的代码:
import nflgame
import copy
players = dict()
qbs = dict()
#get a list of all games in 2014
games = nflgame.games(2014)
#make a list of the players in each game
for g in games:
_p = g.players
for p in _p:
if p.playerid not in players:
players[p.playerid] = p
#find all the qbs in the players
for p in players:
if players[p].guess_position == 'QB' and p not in qbs:
qbs[p] = players[p]
#copy qbs to a list that I can manipulate
unique_qb = []
for v in qbs:
c = copy.deepcopy(qbs[v])
unique_qb.append(c)
print unique_qb[0].name
print unique_qb[0].stats(2015, week=13)#this line produces the error
如何从字典中获得要使用的对象,而不受有序字典中的约束,因此"不可调用"
编辑:
功能
unique_qb[0].stats(2015, week=13)
是对存储在字典条目中的对象的调用,这里是我试图使用的nflgame api中的存根。
def stats(self, year, week=None):
games = nflgame.games(year, week)
players = list(nflgame.combine(games).filter(playerid=self.playerid))
if len(players) == 0:
return GamePlayerStats(self.player_id, self.gsis_name,
None, self.team)
return players[0]
使用[]
而不是()
访问字典。后者用于函数调用。
使用调试器,.stats
是一个返回OrderedDict:的属性
@property
def stats(self):
"""
Returns a dict of all stats for the player.
"""
return self._stats
[Dbg]>>> unique_qb[0].stats
OrderedDict([(u'passing_att', 33), (u'passing_twoptm', 0), (u'passing_twopta', 0), (u'passing_yds', 250), (u'passing_cmp', 22), (u'passing_ints', 0), (u'passing_tds', 2), (u'rushing_lngtd', 0), (u'rushing_tds', 0), (u'rushing_twopta', 0), (u'rushing_lng', -1), (u'rushing_yds', -1), (u'rushing_att', 1), (u'rushing_twoptm', 0)])
由于它是一本字典,您需要[]
。例如:
[Dbg]>>> unique_qb[0].stats['passing_att']
33
由于您描述了一个不同的函数,所以您并没有调用您认为自己是的函数。