简体   繁体   中英

Python: slices of enumerate

I want to iterate within a slice of a list. Also, I want to know the indexes of the element under my iteration.

I want to make something like

for i, elm in enumerate(test_list)[7:40]:
    print i, elm
    #i must start with 7

Alas, it says, that 'enumerate' object has no attribute '__getitem__'

How can I get it in most pythonic way?

enumerate returns an iterator, which does not support index-based access. You can however slice the original list first, and just start at a different index with enumerate :

for i, elm in enumerate(test_list[7:40], 7):
    print i, elm

You can use islice :

from itertools import islice

for i,elm in islice(enumerate(some_list),7,40):
    print i,elm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM