Helena Hepburn
Helena Hepburn

Reputation: 21

Multiply List of RGB values Python

I'm trying to multiply a list of RGB Values, more specifically multiply each element with a different variable e.g.

colors = [(70, 76, 75), (97, 107, 93)]
multipliers = [2,3]
prod = lambda a,b: [a[i]*b[i] for i in range(len(a))]
newcolors = (prod (colors, multipliers))

Desired Output:

[(70,76,75), (70,76,75), (97, 107, 93), (97, 107, 93), (97, 107, 93)] 

But the output I'm getting is

[(70,76,75, 70,76,75), (97, 107, 93, 97, 107, 93,97, 107, 93)]

The returned List does not consist of RGB Values anymore

What seems to be working is

n = 2
newcolors = sorted(colors*n)

Output:

[(70,76,75), (70,76,75), (97, 107, 93), (97, 107, 93)]

But that way all RGB values are multiplied by the same n-amount of times.

Does anybody know how to fix the problem?

Upvotes: 2

Views: 710

Answers (2)

abhiarora
abhiarora

Reputation: 10440

One possible solution using itertools:

import itertools

colors = [(70, 76, 75), (97, 107, 93)]
multipliers = [2,3]

print(list(itertools.chain.from_iterable(map(itertools.repeat, colors, multipliers))))

Output:

[(70, 76, 75), (70, 76, 75), (97, 107, 93), (97, 107, 93), (97, 107, 93)]

Explanation:

Here, map function will apply the values from colors and multipliers to repeat one by one. So, the result of map will be

list(map(repeat, x, y))
[repeat((70, 76, 75), 2), repeat((97, 107, 93), 3)]

Now, we use chain.from_iterable to consume values from each and every iterable from the iterable returned by map.

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use a list comprehension and the built-in function zip, pair with zip each element from colors with each number from multipliers in one for loop, then in a second for loop you are saying how many times the current color should be repeated

[e for e, m in zip(colors, multipliers) for _ in range(m)]

output:

[(70, 76, 75), (70, 76, 75), (97, 107, 93), (97, 107, 93), (97, 107, 93)]

you can also use 2 for loops, with one loop you iterate over each pair (color, multiplier) and in the second/inner loop you are repeating the current color with the current multiplier and extending the result list:

result = []
for e, m in zip(colors, multipliers):
    result.extend([e] * m)
print(result)

output:

[(70, 76, 75), (70, 76, 75), (97, 107, 93), (97, 107, 93), (97, 107, 93)]

Upvotes: 3

Related Questions