Python枚举使用start参数时的内置错误
我正在修改一些代码,这些代码在通过列表理解声明的列表上调用枚举,例如
self.groups = [Groups(self, idx) for idx in range(n_groups)]
稍后:
for idx, group in enumerate(self.groups):
# do some stuff
但是当我将枚举调用更改为通过启动参数从第二个列表元素开始时,例如
for idx, group in enumerate(self.groups[1]):
我得到一个异常:
exceptions.TypeError: 'Group' object is not iterable
有人可以解释为什么会这样吗?是?
I'm modifying some code that calls enumerate on a list declared via a list comprehension e.g.
self.groups = [Groups(self, idx) for idx in range(n_groups)]
then later:
for idx, group in enumerate(self.groups):
# do some stuff
but when I change the enumerate call to start at the 2nd list element via the start parameter e.g.
for idx, group in enumerate(self.groups[1]):
I get an exception:
exceptions.TypeError: 'Group' object is not iterable
Could someone explain why this is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题:在序列上使用带有单个参数的索引器将从序列中生成一个单个对象。从序列中选取的对象属于
Group
类型,并且该类型不可迭代。解决方案:使用 slice 构造 获取新的特定索引中的项目序列:
The problem: Using an indexer with a single argument on a sequence will yield a single object from the sequence. The object picked from your sequence is of type
Group
, and that type is not iterable.The solution: Use the slice construct to get a new sequence of items from a specific index:
您不是从第二个开始,而是尝试仅迭代第二个。要从第二项开始,请执行以下操作:
you're not starting at the second, you're trying to iterate only over the second. To start at the second item do:
如果您的序列足够大,请考虑使用
itertools
模块中的islice
函数,因为对于大型序列来说,它比切片更节省内存:If your sequence is large enough than consider using
islice
function fromitertools
module, because it's more memory efficient for large sequences than slicing: