gpt4 book ai didi

python - 具有唯一属性的对象列表

转载 作者:太空狗 更新时间:2023-10-29 17:11:23 24 4
gpt4 key购买 nike

我有一个对象列表,每个对象都有一个特定的属性。该属性不是唯一的,我希望最终得到一个对象列表,它是整个列表的一个子集,这样所有特定属性都是一个唯一的集合。

例如,如果我有四个对象:

object1.thing = 1
object2.thing = 2
object3.thing = 3
object4.thing = 2

我想结束任何一个

[object1, object2, object3]

[object1, object3, object4]

出现在最终列表中的确切对象并不重要,重要的是其特定属性的列表是唯一的。

编辑:澄清一下,本质上我想要的是一个与该特定属性绑定(bind)的集合。

最佳答案

您可以使用列表理解集合:

objects = (object1,object2,object3,object4)
seen = set()
unique = [obj for obj in objects if obj.thing not in seen and not seen.add(obj.thing)]

上面的代码等价于:

seen = set()
unique = []
for obj in objects:
if obj.thing not in seen:
unique.append(obj)
seen.add(obj.thing)

关于python - 具有唯一属性的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17347678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com