【发布时间】:2011-11-17 15:26:57
【问题描述】:
我想要一个字典或元组,我可以根据我用作 *arg 的参数的对象的属性进行排序。我一直在尝试这样做的方式只是给了我 AttributeErrors,这让我相信我这样做很奇怪。
def function(*arg):
items = {}
for thing in arg:
items.update({thing.name:thing})
while True:
for thing in items:
## lots of other code here, basically just a game loop.
## Problem is that the 'turn order' is based on whatever
## Python decides the order of arguments is inside "items".
## I'd like to be able to sort the dict based on each object's
## attributes (ie, highest 'thing.speed' goes first in the while loop)
问题是当我尝试根据放入函数()的对象的属性对“项目”进行排序时,它给了我“AttributeError:'str'对象没有属性'attribute'”。这让我相信我要么以糟糕的方式解包 *arg,要么试图以错误的方式做某事。
while True:
for thing in sorted(items, key=attrgetter('attribute')):
...也不起作用,一直告诉我我正在尝试操作“str”对象。我不在这里做什么?
【问题讨论】:
-
不要使用
update将项目一个一个地添加到dict- 它是为了从序列/迭代器更新现有的dict。有关如何创建新的dict(这也是您使用update添加到现有dict的方式),请参阅我的答案,或者稍后使用items[thing.name] = thing向其中添加单个项目。 -
你能描述一下你的函数的参数吗?对我来说,
AttributeError与非法输入类型相关联(如str)。
标签: python sorting dictionary tuples