简体   繁体   English

python 可迭代是否暗示可数?

[英]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个问题:

  1. In Python, does iterable => countable (number of items)?在 Python 中,是否可迭代 => 可计数(项目数)? Or is it just very common to be so?还是这样很常见?

  2. 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.

相关问题 python yield暗示继续吗? - Does python yield imply continue? 在 Python 中 close() 是否意味着 flush() ? - does close() imply flush() in Python? 在Python中,线程安全通常是否意味着绿色安全? - Does thread-safe generally imply greenlet-safe in Python? 一个 Python for 循环是如何工作的? - How does a Python for loop with iterable work? 为什么 Python 允许解压缩空的可迭代对象? - Why does Python allow unpacking an empty iterable? python 中的方法与类相关联。 与实例直接关联的函数意味着什么? - Methods in python are associated with the class. what does a function associated directly with the instance imply? 为什么python的结构认为little-endian和big-endian暗示了不同的长度? - Why does python's struct think little-endian and big-endian imply different lengths? Python 中的“可迭代”究竟是什么意思? 为什么我的实现 `__getitem__()` 的对象不是可迭代的? - What exactly does "iterable" mean in Python? Why isn't my object which implements `__getitem__()` an iterable? 在对可迭代对象进行排序时,Python如何打领带 - How does Python break tie when sorting an iterable 为什么在类上定义 __getitem__ 使其在 python 中可迭代? - Why does defining __getitem__ on a class make it iterable in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM