-1

Perhaps this was asked before in which case I will remove this question but I have two lists:

occurence_list = [1, 2, 3, 4, 5]
value_list = [10, 20, 30, 40, 50]

And I want each value to appear the same number of times as the value of the same index from the other list:

result = [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]

How can this be done?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Joseph
  • 586
  • 1
  • 13
  • 32
  • very similar to this: http://stackoverflow.com/questions/25156745/list-comprehension-to-repeat-element-in-a-list-by-element-value – EdChum Mar 09 '17 at 10:42

2 Answers2

5

Use itertools.repeat() and chain():

In [6]: from itertools import repeat, chain

In [7]: list(chain.from_iterable(repeat(i, j) for i, j in zip(value_list, occurence_list)))
Out[7]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]

Instead of concatenating the repeat objects by chain.from_iterable and then converting the result to list you can also use a nested list comprehension:

In [12]: [t for i, j in zip(value_list, occurence_list) for t in repeat(i, j)]
Out[12]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

Use list comprehension,

In [7]: [j for i,j in enumerate(value_list) for _ in range(occurence_list[i])]

Out[7]: [10, 20, 20, 30, 30, 30, 40, 40, 40, 40, 50, 50, 50, 50, 50]
Rahul K P
  • 15,740
  • 4
  • 35
  • 52