将 Python 对象列表减少为 object.id 的字典 ->目的

发布于 2024-09-06 07:54:28 字数 185 浏览 5 评论 0原文

您有对象列表,每个对象都有一个 id 属性。

这是我将其转换为 dict 的方法,其中键是 id,值是对象:

reduce(
  lambda x,y: dict(x.items() + { y.id : y}.items()),
  list,
  {}
)

建议更好的方法。

You have list of objects and each of them has an id property.

Here's my way to convert it to dict where keys are ids and values are objects:

reduce(
  lambda x,y: dict(x.items() + { y.id : y}.items()),
  list,
  {}
)

Suggest better way to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

柏林苍穹下 2024-09-13 07:54:28

在 Python 3.x 中:

object_dict = {x.id: x for x in object_list}

在 Python 3.x 和 Python 2.4+ 中:

object_dict = dict((x.id, x) for x in object_list)

(x.id, x) for x in object_list 是生成器理解(而且,很好的是,不需要包装如果将其用作调用的单个参数,则需要将其放在括号中,例如列表理解,当然,这意味着在其他情况下我使用的表达式必须是 ((x.id, x) 表示 object_list 中的 x))。与列表理解不同,它不会生成所有项目的实际列表,因此在这种情况下更有效。

附带说明一下,Python 有一个内置方法 id():

返回对象的“身份”。这是一个整数,保证该对象在其生命周期内是唯一且恒定的。具有不重叠生命周期的两个对象可能具有相同的 id() 值。 (实现说明:这是对象的地址。)

因此,如果您想让 Python 自己处理 ids,您可以这样做:

object_dict = {id(x): x for x in object_list}

object_dict = dict((id(x), x) for x in object_list)

In Python 3.x:

object_dict = {x.id: x for x in object_list}

In both Python 3.x and Python 2.4+:

object_dict = dict((x.id, x) for x in object_list)

(x.id, x) for x in object_list is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to be wrapped in brackets if it's being used as a single argument for a call; of course, this means that in other circumstances the expression I used would have to be ((x.id, x) for x in object_list)). Unlike a list comprehension, it will not generate an actual list of all the items, and is thus more efficient in situations such as this.

As a side note, Python has a built-in method id():

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)

So if you wanted to let Python handle the ids on its own, you could do it as:

object_dict = {id(x): x for x in object_list}

or

object_dict = dict((id(x), x) for x in object_list)
病毒体 2024-09-13 07:54:28
dict([(x.id, x) for x in list])
dict([(x.id, x) for x in list])
戴着白色围巾的女孩 2024-09-13 07:54:28
dict(map(lambda x: [x.id, x], list))
dict(map(lambda x: [x.id, x], list))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文