在“any()”之后不保留迭代器值称呼
我有以下代码片段。我基本上试图获取列表中特定字符串的索引/迭代器(除了只知道它是否存在)。这是否可能,或者我应该使用带有 if 的循环?
Bucket = ["alpha", "beta", "gamma"]
content = ""
如果有的话(对于存储桶中的内容,内容 == "beta"): 打印内容
将“内容”设置为全局或仅在循环内并没有什么区别
I have the following snippet of code. I'm basically trying to get the index/iterator of a particular string in a list (aside from just knowing whether it is present). Is this possible at all, or should I be using a loop-with-an-if?
bucket = ["alpha", "beta", "gamma"]
content = ""
if any(content == "beta" for content in bucket):
print content
Having 'content' as global or simply within the loop did not make a difference
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在创建一个生成器,用于在
any
调用中进行搜索。您留下的那个发电机是临时的。也就是说,它仅存在于对any
的调用中,因此您之后将无法查看它。如果您希望它出现在索引的位置,请执行以下操作:生成所有匹配项加上索引的列表。
You are creating a generator for searching within the
any
call. That generator as you have left it is a temporary. That is, it exists only within the call toany
so you will not be able to look at it afterwards. If you want it to come out to the location of the index then do this:which generates the list of all items which match plus the indexes.
生成器表达式不会泄漏迭代器。列表推导式在 2.x 中可以,但在 3.x 中不行。
Generator expressions do not leak the iterator. List comprehensions in 2.x do, but not in 3.x.