Semi-random order to avoid repetition of grouping variable

Hi,

I’m presenting audio stimuli that are in two groups. I want presentation to be mostly random but to avoid excessive repetition of the two groups (let’s say no more than 3 repeats of same type).

Here is a small example of what stimuli look like (there are actually 24 of each type, 48 total):
image

I’ve used this thread as a starting point

But it shows how to shuffle items within an array. I want to shuffle items based on another condition (the type column).
Can I do this within a builder loop? Meaning cheat a little by using the loop for iteration but use a custom code component to select the stimulus. Here is the structure of the loop I’m using
image

The audio happens in the “trials” routine. Because I have two other routines in the same loop I’d really prefer to preserve the builder loop if possible.

I can’t think of the best way to tie the indices of the ‘type’ and ‘melodies’, i.e. letting me check type but shuffle both together. Does PsychoPy store imported xls and csv files in a format I can access and manipulate?
Any recommendations based on the code in the example above would be useful. Or if you see a simple solution I’m missing. My python skills are limited and I intend to run this online so I’d like to keep it simple to make the Java conversion less painful.

Any help appreciated!

You can load spreadsheets into a list you can manipulate.

Have a look an my Independent Randomisation demo here: