简体   繁体   中英

Access items in enumerate by index

As part of a project, I need to reference specific values in an iterable by their index. Unfortunately, this iterable doesn't have a __getitem__() method defined, so I don't have a way of directly doing this. So far, I've been using enumerate() to get the indices, but unfortunately that doesn't give me a subscriptable object (for reasons that I don't understand, the package I'm working with really doesn't like it when I cast the enumerate to a list either, so that option's out). So far my best solution is this:

goodEvs=[(i,ev) for i,ev in enumerate(events) if i in flags]

where flags is a list of the indices that I want to keep. Unfortunately, iterating through all of events takes a very long time, so I'd like to be able to do something like this:

goodEvs=[events[i] for i in flags]

but then I run into subscriptability problems. Sorry for the very weird and specific constraints, I think we're starting to stretch what this package can do (or I'm just bad at this). Thanks!

I just realized that the problem actually runs deeper than what I've been asking about. Thanks so much to everyone for the fast response, but I think I need to go back to the drawing board. I'll be closing this topic as soon as I can figure out how to

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