迭代器的成员资格测试 [英] Membership test for iterators

查看:84
本文介绍了迭代器的成员资格测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以在下面的代码的最后三行中向我解释成员资格测试的行为,为什么它为False? 为什么对迭代器和可迭代对象的成员资格测试有所不同?

Can somebody explain me the behaviour of membership test in the last 3 lines of my code bellow, why is it False? Why is the membership test different for iterators and iterables?

c = [1,2,3,4,5,6,7,8,9,10,11,12]

print(3 in c)   # True
print(3 in c)   # True

d = iter(c)
print(2 in d)   # True
print(4 in d)   # True
print(4 in d)   # False  ???
print(6 in d)   # False  ???
print(10 in d)   # False  ???

推荐答案

迭代器在使用时被消耗.我将在您的示例中进行解释:

Iterators are consumed when used. I'll explain on your example:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> print(list(d))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> print(list(d))
[]

您可以将迭代器d视为指向列表中第一项的指针.读取其值后,它指向第二项.当到达末尾时,它指向一个空列表.

You can think of the iterator d as of a pointer to the first item in the list. Once you read its value, it points to the second item. When it reaches the end, there it points to an empty list.

另请参阅:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> print(next(d))
1
>>> print(next(d))
2
>>> print(list(d))
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

检查其中是否还包含一些内容:

Checking whether something is in it also consumes its contents:

>>> c = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> d = iter(c)
>>> 4 in d
True
>>> print(list(d))
[5, 6, 7, 8, 9, 10, 11, 12]

这篇关于迭代器的成员资格测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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