Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以从对象列表中引用对象?_Python_List_Object - Fatal编程技术网

Python 是否可以从对象列表中引用对象?

Python 是否可以从对象列表中引用对象?,python,list,object,Python,List,Object,我有一个如下形式的对象列表 a = [<__main__.Card at 0x10b47a630>, <__main__.Card at 0x10b47aba8>, <__main__.Card at 0x10b47ac18>, <__main__.Card at 0x10b47a588>, <__main__.Card at 0x10b47a0f0>, <__main__.Car

我有一个如下形式的对象列表

a = [<__main__.Card at 0x10b47a630>,
     <__main__.Card at 0x10b47aba8>,
     <__main__.Card at 0x10b47ac18>,
     <__main__.Card at 0x10b47a588>,
     <__main__.Card at 0x10b47a0f0>,
     <__main__.Card at 0x10b47a208>]
我知道我可以用字符串来实现这一点:

a = ['a', 'b', 'c', 'z']

a.remove('c')

a = ['a', 'b', 'z']
然而,我还没有弄明白在这种情况下该怎么做

我知道我可以这样做:

a.remove(a[0])

但我不确定应该采用的对象形式。删除。

任何从对象列表中分配元素的变量实际上都有对该对象的引用,下面是一个示例,说明如何在不使用索引的情况下从对象列表中删除对象:

from random import choice


class Test:
    def __init__(self, x):
        self.x = x
    def __repr__(self):
        return f'Test(x={self.x})'

l = [Test(i) for i in range(5)]
print(l)

obj = choice(l)
print(obj)
l.remove(obj)
print(l)
输出:

[Test(x=0), Test(x=1), Test(x=2), Test(x=3), Test(x=4)]
Test(x=1)
[Test(x=0), Test(x=2), Test(x=3), Test(x=4)]
假设

a = [<__main__.Card at 0x10b47a630>,
     <__main__.Card at 0x10b47aba8>,
     <__main__.Card at 0x10b47ac18>,
     ...
其中obj.birthmark是区别特征,mole是标记要移除的对象的值

或者,您可以使用上面的列表删除对象,而无需使用“删除”:


您需要像往常一样以某种方式引用对象,因为默认情况下,您的类将使用标识来表示相等。你可以用另一种方式定义相等,并传递相等的对象a.remove'c'示例删除对象的标准是什么?你需要以某种方式区分。如果你知道位置,为什么不a.pop0?@Jean-Françoisfare他不知道位置,这只是一个例子。参见
a = [<__main__.Card at 0x10b47a630>,
     <__main__.Card at 0x10b47aba8>,
     <__main__.Card at 0x10b47ac18>,
     ...
obj_to_remove = [obj for obj in a if obj.birthmark == "a mole"][0]
a.remove(obj_to_remove)
a = [obj for obj in a if obj.birthmark != "a mole"]