简体   繁体   English

按索引访问项

[英]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. 不幸的是,此可迭代方法没有定义__getitem__()方法,因此我没有直接进行此操作的方法。 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). 到目前为止,我一直在使用enumerate()来获取索引,但是不幸的是,这并没有给我提供可下标的对象(由于我不明白的原因,我正在使用的程序包确实不喜欢它当我将枚举类型转换为列表时,该选项将消失。 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. 其中flags是我要保留的索引列表。 Unfortunately, iterating through all of events takes a very long time, so I'd like to be able to do something like this: 不幸的是,遍历所有events需要很长时间,因此我希望能够执行以下操作:

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 我将尽快弄清如何关闭该主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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