简体   繁体   English

按 id 从对象列表中检索

[英]Retrieving from list of objects by id

In the following code I create a list of three objects and use the variable a,b,c to store the first, second and then the third object by their id's but when I try to store the third object in variable c, it stores a list of the second and third object.在下面的代码中,我创建了一个包含三个对象的列表,并使用变量 a、b、c 通过它们的 id 存储第一个、第二个和第三个对象,但是当我尝试将第三个对象存储在变量 c 中时,它存储了一个第二个和第三个对象的列表。

class Obj1():
    id='obj1'

class Obj2():
    id='obj2'

class Obj3():
    id='obj3'

list1=[Obj1(),Obj2(),Obj3()]

a=list1[id=="obj1"]
print a

b=list1[id!='obj1']
print b

c=list1[id!='obj1'and id!='obj2':]
print c

When I run this code I get :当我运行此代码时,我得到:

<__main__.Obj1 instance at 0x02AD5DA0>
<__main__.Obj2 instance at 0x02AD9030>
[<__main__.Obj2 instance at 0x02AD9030>, <__main__.Obj3 instance at 0x02AD90A8>]

why does variable c contain two objects?为什么变量 c 包含两个对象?

Using a dictionary is probably the best idea in this case, as mentioned by Medhat.正如 Medhat 所提到的,在这种情况下使用字典可能是最好的主意。 However, you can do things in a similar way to what you attempted using list comprehensions:但是,您可以使用与您尝试使用列表推导类似的方式执行操作:

a = [e for e in list1 if e.id == "obj1"]
print a

b = [e for e in list1 if e.id != "obj1"]
print b

c = [e for e in list1 if e.id != "obj1" and e.id != "obj2"]
# Or:
# [e for e in list1 if e.id not in ("obj1", "obj2")]
print c

id!='obj1'and id!='obj2' returns true which equals 1 in Python, that is to say, c=list1[id!='obj1'and id!='obj2':] equals c=list1[1:] , which of course has two objects. id!='obj1'and id!='obj2'在 Python 中返回 true 等于 1,也就是说c=list1[id!='obj1'and id!='obj2':]等于c=list1[1:] ,当然有两个对象。

BTW, id is the name of a built-in function.顺便说一句, id是内置函数的名称。 Please avoid using it as a name of varible.请避免将其用作变量的名称。

You should use a dictionary instead:您应该改用字典:

obj1 = Obj1()
obj2 = Obj2()
obj3 = Obj3()
list1 = {obj1.id: obj1, obj2.id: obj2, obj3.id: obj3}

Then access your objects like this:然后像这样访问您的对象:

a = list1[obj1.id]
b = list1[obj2.id]
c = list1[obj3.id]

Your list1 contains 3 elements:您的 list1 包含 3 个元素:

>>> list1
[<__main__.Obj1 instance at 0x103437440>, <__main__.Obj2 instance at 0x1034377a0>,         <__main__.Obj3 instance at 0x103437320>]
>>> id!='obj1'
True
>>> id!='obj2'
True
>>> True and True
True
>>> list1[True:]
[<__main__.Obj2 instance at 0x1034377a0>, <__main__.Obj3 instance at 0x103437320>]
>>>

True is 1 and False is 0 index: True 为 1,False 为 0 索引:

Here is the example:这是示例:

>>> ls = [1,2]
>>> ls[True]
2
>>> ls[False]
1
>>>

So, list[True:] is equal to list[1:] which is from first element till last.因此, list[True:] 等于 list[1:] 从第一个元素到最后一个元素。

In your case the the last two elements in the list1.在您的情况下,list1 中的最后两个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM