Randomly selecting n items from lists and shuffling them

OS: macOS Monterey (12.6.3)
Psychopy standard standalone: v2022.2.5.

What are you trying to achieve?
I am building an experiment on builder to then transfer it online.
To select the stimuli, I have introduced a code component at the beginning of my experiment. The python code works just fine when run as a local python program.

It does the following:

I have five lists with 5 items in each. It then chooses three random items from each list (without repetitions) and shuffles them. This final list is the list with my stimuli.

This is the python code:

import random

rp_sp = ["rp/rp1.wav","rp/rp2.wav","rp/rp3.wav","rp/rp4.wav","rp/rp5.wav"]
pl_sp = ["pl/pl1.wav","pl/pl2.wav","pl/pl3.wav","pl/pl4.wav","pl/pl5.wav"]
ld_sp = ["ld/ld1.wav","ld/ld2.wav","ld/ld3.wav","ld/ld4.wav","ld/ld5.wav"]
fr_sp = ["fr/fr1.wav","fr/fr2.wav","fr/fr3.wav","fr/fr4.wav","fr/fr5.wav"]
ch_sp = ["ch/ch1.wav","ch/ch2.wav","ch/ch3.wav","ch/ch4.wav","ch/ch5.wav"]

list_stimuli = random.sample(rp_sp,3)+random.sample(pl_sp, 3)+random.sample(ld_sp, 3)+random.sample(fr_sp, 3)+random.sample(ch_sp, 3)

random.shuffle(list_stimuli)
print(list_stimuli)

What did you try to make it work?
It works fine when I run it in python on my computer. But the issues come when trying to do it online.

When I first tried it online by simply having the automatic translation, it did not work. I tried simply deleting “import random”, just to see what happens. But then it says the object “list_stimuli” doesn’t exist.

I managed to find out that “import random” does not work on js. But I still haven’t been able to find how to use the python “random.sample” and “random.shuffle” in js. I have seen those crib sheets by wakecarter. But those examples of random do not apply to my case (the way I understand it).

Hello kevin_clark

I did not try this online.

rp_sp = ["rp/rp1.wav","rp/rp2.wav","rp/rp3.wav","rp/rp4.wav","rp/rp5.wav"]
pl_sp = ["pl/pl1.wav","pl/pl2.wav","pl/pl3.wav","pl/pl4.wav","pl/pl5.wav"]

shuffle(rp_sp)
shuffle(pl_sp

rp_sp3 = [rp_sp[i] for i in (0, 1, 2)]
pl_sp3 = [pl_sp[i] for i in (0, 1, 2)]

combi = rp_sp3 + pl_sp3
shuffle(combi)

But this might do the trick.

Best wishes Jens

1 Like

That made it work. Thank you very much! The only thing I needed to modify is how I combine the lists. The automatic translation from python ( (((lista+listb)+listc)+listd) ) does not work. So I had to do it the js way lista.concat(listb,listc,listd).

After that, it worked like a charm!

Hello,

there are too many ways in Python to concatenate lists. Perhaps it is better to use

for x in pl_sp3:
    rp_sp3.append(x)

Best wishes Jens