I have an iterator iterator and a list of indices indices (repeats possible) and I want to extract just those elements from my iterator. At the moment I'm doing
indices = sorted(indices)
deltas = [indices[0]] + [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
output = []
for delta in deltas:
for i in range(delta):
datum = next(iterator)
output.append(datum)
Are those two layers of loop necessary? Am I missing a trick with itertools?
ints, but this line:indices[0] + [indices[i+1] - indices[i] for i in range(len(indices) - 1)]will not work if that is the case - you can't add alistto anint.iteratorsare for a single pass over a sequence: if you are going to be repeating indices why not index directly into the sequence?itertoolsfunctions likeislicewon't work for you since you may have repeated indices. One thing to consider though: if theiteratorcontains only a modest amount of data (not more than can fit in memory, and not orders of magnitude more than the number of indices), it might be easier to simply consume it all to populate a list, and use a trivial list comprehension to get the requested values.