开发者

Python enumerate built-in error when using the start parameter

开发者 https://www.devze.com 2022-12-25 09:48 出处:网络
I\'m modifying some code that calls enumerate on a list dec开发者_StackOverflow中文版lared via a list comprehension e.g.

I'm modifying some code that calls enumerate on a list dec开发者_StackOverflow中文版lared 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?


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:

for idx, group in enumerate(self.groups[1:]):
    # do some stuff


you're not starting at the second, you're trying to iterate only over the second. To start at the second item do:

for idx, group in enumerate(self.groups[1:]):
    # process


If your sequence is large enough than consider using islice function from itertools module, because it's more memory efficient for large sequences than slicing:

import itertools

for idx, group in enumerate(itertools.islice(self.groups, 1, None)):
    # process
0

精彩评论

暂无评论...
验证码 换一张
取 消