Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating list using a frequency list in Python [duplicate]

age = [19, 20, 21, 22, 23, 24, 25]
frequency = [2, 1, 1, 3, 2, 1, 1]
output_age = [19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

How do we create a new list which adds items from one list a number of times dependant on another list?

Thanks

like image 287
jr100 Avatar asked Dec 04 '22 19:12

jr100


1 Answers

Use a list-comprehension:

output_age = [i for l in ([a]*f for a, f in zip(age, frequency)) for i in l]
#[19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]

why?

We first zip together the age and frequency lists so we can iterate over them in unison. As so:

for a, f in zip(age, frequency):
    print(a, f)

gives:

19 2
20 1
21 1
22 3
23 2
24 1
25 1

Then we want to repeat each element, a, as many times as f determines. This can be done by creating a list and multiplying it. Just like:

[4] * 3
#[4, 4, 4]

We then need to unpack these values so we wrap this expression in a generator (indicated with brackets) and iterate over that. This flattens the list. Note that there are alternative ways of achieving this (such as using itertools.chain.from_iterable).


An alternative method would be to repeat the number, a, through iterating over a range object rather than multiplying a list to get the repetitions.

This method would look something like:

output_age = [a for a, f in zip(age, frequency) for _ in range(f)]
#[19, 19, 20, 21, 22, 22, 22, 23, 23, 24, 25]
like image 62
Joe Iddon Avatar answered Dec 15 '22 00:12

Joe Iddon