pythonindexingpsychopy

Python. Index through a list by random set size specified in another list


I want to loop through a list of words in different set sizes, and the order of the set size is specified in another list. I want to jump to the new word in the word list after each trial set.
For example, I have

stimuli_words = ["tree","bird","cake","ocean","dance","statistics","headphone", "red","duck"]

and I have set_size = [2, 4, 3]

I use chosen_size = +1 to loop through the set_size list. I want the first trial to show "tree","bird", second trial to show "cake","ocean","dance","statistics", and third trial to show "headphone", "red","duck", how should I do this?


Solution

  • I think a helper function would be appropriate:

    def chunks_with_sizes(li, sizes):
        i = 0
        for sz in sizes:
            yield li[i:i+sz]
            i += sz
    

    Then:

    >>> list(chunks_with_sizes(stimuli_words, set_size))
    [['tree', 'bird'], ['cake', 'ocean', 'dance', 'statistics'], ['headphone', 'red', 'duck']]