社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

Daniel Konstantinov

Daniel Konstantinov 最近创建的主题
Daniel Konstantinov 最近回复了
4 年前
回复了 Daniel Konstantinov 创建的主题 » 当元素包含numpy数组时,无法测试python列表元素的成员身份

简化:

def my_in(obj, container):
    for elem in container:
        if bool(my_compare_equal(obj, elem)):
            return True
    return False

def my_compare_equal(obj, elem):
    if id(obj) == id(elem):
        return True
    return obj.__eq__(elem)

有关更多数据,请参阅 list_contains 然后 PyObject_RichCompareBool , PyObject_RichCompare , do_richcompare

“伪执行”步骤:

c = [AA('x', np.arange(3)),
     AA('x', np.arange(3)),
     AA('y', np.arange(3))]

c[0] in c
# explain:
my_in(obj=c[0], container=c)
    # for loop:
    
    # 0-iteration:
    # elem = c[0]
    my_compare_equal(obj=c[0], elem=c[0])
        # (id(c[0]) == id(c[0])) == True
        # --> True
    bool(True)
        # True.__bool__()
        # --> True
    # --> True

c[1] in c
# explain:
my_in(obj=c[1], container=c)
    # for loop:

    # 0-iteration:
    # elem = c[0]
    my_compare_equal(obj=c[1], elem=c[0])
        # (id(c[1]) == id(c[0])) == False
        # c[1].__eq__(c[0])
            # compare tuples element by element:
            # 0-iteration:
            my_compare_equal('x', 'x') == True
            # 1-iteration:
            my_compare_equal(np.arange(3), np.arange(3))
                # (id(np.arange(3)) == id(np.arange(3))) == False
                # np.arange(3).__eq__(np.arange(3))
                # --> np.ndarray([True, True, True])
            bool(np.ndarray([True, True, True]))
                # np.ndarray([True, True, True]).__bool__()
                    raise ValueError("The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()")

c[2] in c
# explain:
my_in(obj=c[2], container=c)
    # for loop:

    # 0-iteration:
    # elem = c[0]
    my_compare_equal(obj=c[2], elem=c[0])
        # (id(c[2]) == id(c[0])) == False
        # c[2].__eq__(c[0])
            # compare tuples element by element:
            # 0-iteration:
            my_compare_equal('y', 'x') == False
            # --> False
        # --> False

    # 1-iteration:
    # analogiusly as 0-iteration:
    my_compare_equal(obj=c[2], elem=c[1])
        # --> False
    
    # 2-iteration:
    my_compare_equal(obj=c[2], elem=c[2])
        # (id(c[2]) == id(c[2])) == True
        # --> True
    # --> True