列表成员的详细信息 [英] Specifics of List Membership

查看:63
本文介绍了列表成员的详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python(特别是2.6.4)如何一般确定列表成员身份?我已经进行了一些测试以查看其作用:

How does Python (2.6.4, specifically) determine list membership in general? I've run some tests to see what it does:

def main():
    obj = fancy_obj(arg='C:\\')
    needle = (50, obj)
    haystack = [(50, fancy_obj(arg='C:\\')), (1, obj,), needle]

    print (1, fancy_obj(arg='C:\\'),) in haystack
    print needle in haystack

if __name__ == '__main__':
    main()

哪个产量:

False
True

这告诉我Python可能正在检查对象引用,这很有意义.我还能看些更确定的东西吗?

This tells me that Python is probably checking the object references, which makes sense. Is there something more definitive I can look at?

推荐答案

来自(非官方)Python参考Wiki :

对于列表和元组类型,当且仅当存在一个索引i使得x == y[i]为true时,x in y为true.

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

因此,在您的示例中,如果fancy_obj类将arg的值存储在实例变量中,并且要实现一个__eq__方法,如果比较的两个fancy_objs具有相同的值,则该方法返回True. arg,则(1, fancy_obj(arg='C:\\'),) in haystack为True.

So in your example, if the fancy_obj class stored the value of arg in an instance variable and were to implement an __eq__ method that returned True if the two fancy_objs being compared had the same value for arg then (1, fancy_obj(arg='C:\\'),) in haystack would be True.

标准库参考的相关页面为:内置类型,特别是 5.6序列类型

The relevant page of the Standard Library reference is: Built-in Types, specifically 5.6 Sequence Types

这篇关于列表成员的详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆