You just need to create a list that maps an index to a file and to a sample, for this you will have to iterate over the complete dataset once, and build this map at the same time.
You will also have to write the def __getitem__(self, index): in the same way.