[英]Does python iterable imply countable?
I've stumbled upon an interesting case - only thing I am sure about is that I will get an iterable
object.我偶然发现了一个有趣的案例——我唯一确定的是我会得到一个
iterable
的 object。
What I really, and only, want to do is to count it.我真正并且唯一想做的就是数一数。
I've searched if iterable in python implies countable and I found various places claiming so, except the official docs.我已经搜索了 python 中的可迭代是否意味着可数,我发现除了官方文档之外的各个地方都声称如此。
So 2 questions arise:所以出现了2个问题:
In Python, does iterable => countable (number of items)?在 Python 中,是否可迭代 => 可计数(项目数)? Or is it just very common to be so?
还是这样很常见?
Is there a generic pythonic way to get count from an iterable?是否有一种通用的 Pythonic 方法可以从可迭代对象中获取计数? Which seems to be answered here https://stackoverflow.com/a/3345807/1835470 ie not without counting, but author provided a pythonic one-liner:
这似乎在这里得到了回答https://stackoverflow.com/a/3345807/1835470即不是没有计数,但作者提供了一个 pythonic 单行:
sum(1 for _ in iterableObject)
iterables
do not support the len
method. iterables
不支持len
方法。 To get their length you have to cast them into something that does support it or manually loop through them (and exhaust them in the process) while counting such as in this code snippet you posted.要获得它们的长度,您必须将它们转换成支持它的东西或手动循环它们(并在过程中耗尽它们)同时计数,例如您发布的此代码片段。
As a result, the requirement of using an iterable and needing to know its length is somewhat conflicting.因此,使用可迭代对象和需要知道其长度的要求有些矛盾。 Plus as @Veedrac says in the comments, iterables can have infinite length .
另外,正如@Veedrac 在评论中所说,可迭代对象可以有无限长度。
To sum up, if you need to know how many items are contained, you need a different data structure.总而言之,如果您需要知道包含多少项,则需要不同的数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.