I want to generate a list of strings shown below:

['EEG', 'EEG', 'EEG', 'EMG', 'EMG', 'EOG']

but, for example, with 32 'EEG' items and 2 'EMG' and one 'EOG'. How could I do that in one line?

I have read a StackOverflow post and I know a single repeated element can be generated with the code below:

['EEG']*32

or

['EEG' for _ in range(32)]

But I want a comprehensive list of all items with different frequencies. I want a flat list of different items, not a nested list of lists.

5 Answers

2
Bazingaa On Best Solutions

You can repeat a list element using multiplication operator and then just add the lists together

answer = ['EEG']*32 + ['EMG']*2 + ['EOG']  
# ['EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EMG', 'EMG', 'EOG']
1
kudeh On

Use the multiplication operator then concatenate, like so:

['EEG']*32 + ['EMG']*2 + ['EOG']
1
blhsing On

You can use the collections.Counter.elements method:

from collections import Counter
list(Counter(EEG=32, EMG=2, EOG=1).elements())

This returns:

['EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EEG', 'EMG', 'EMG', 'EOG']
0
AlexYes On

dynamic way to do this would be:

config = [{"str":"EEG","freq":32},{"str":"EMG","freq":2},{"str":"EOG","freq":1}]
[item for sublist in ([[x["str"]]*x["freq"] for x in config]) for item in sublist]

to break this down:

config is an array of objects where str key is the string and freq key is the number of times you'd like to repeat it

([[x["str"]]*x["freq"] for x in config]) returns an array of arrays of repeated strings

the outer part flattens this complex array into a simple list

0
Community On

You can either use the multiplication operator and then concatenate each list like this:

list = ['EEG'] * 32 + ['EMG'] * 2 + ['EOG']

Or you could also import Counter from collections, like another user stated, like this:

from collections import Counter
list(Counter(EEG=32, EMG=2, EOG=1).elements())

Both of these would yield a list containing 32 'EEG', 2 'EMG' and 1 'EOG'