0

I searched a lot for an answer, but I can only find answers on just adding one item multiple times. Or just multiplying two lists.

#ratio of bar
ratio_variant1 = 0.1
ratio_variant2 = 0.3
ratio_variant3 = 0.4
ratio_variant4 = 0.2

ratio = []
ratio.extend([ratio_variant1, ratio_variant2, ratio_variant3, ratio_variant4])

#ratio to integer
ratiointeger = [x*100 for x in ratio]

#size of bar
size_variant1 = 2
size_variant2 = 3
size_variant3 = 4
size_variant4 = 6

size = []
size.extend([size_variant1, size_variant2, size_variant3, size_variant4])

bucket = size * ratiointeger

I'm afraid that my way of creating the ratio and size list are not really pythonic, but the main problem is that I'm not able to make a list/bucket with:

10 items of 2
30 items of 3
40 items of 4
20 items of 6

2 Answers2

0

Try this:

bucket = [[s] * int(r) for (s, r) in zip(size, ratiointeger)]

Szabolcs
  • 3,990
  • 18
  • 38
0

It seems to me you need:

bucket = [x for l in ([s]*r for s, r in zip(size, ratiointeger)) for x in l]

This builds a list of lists, containing the repetitions you want:

>>> [[s]*r for s, r in zip(size, ratiointeger)]
[[2, 2, 2, 2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6]]

Then flattens them using the method from this post.

Community
  • 1
  • 1
muru
  • 4,723
  • 1
  • 34
  • 78
  • That is what I needed, at least I don't need numPy for it. Do you also have a suggestion for creating the ratio and size array in a more pythonic way? – Marc den H Mar 02 '17 at 12:03
  • @MarcdenH honestly, I don't know why you wrote it that way instead of, say, `ratiointeger = [x*100 for x in [0.1, 0.3, 0.4, 0.2]]`. I assumed you had some reason for it. – muru Mar 02 '17 at 12:05
  • I think it goes wrong when declaring everything separate. It was meant to make everything clear, I need to change the ratio and size multiple times. So that is why I declared them so explicit. – Marc den H Mar 02 '17 at 12:13