I have a partition of the set {0,1,…,n-1} into a list of m subsets along corresponding to m colors. I need to assign each index in my set to the corresponding color.
As a simple example, if n=8 and m=3, let
partition=[{0,2},{1,4,6},{3,5,7}]
colors=['r','b','c']
I want to create the list ['r','b','r','c','b','c','b','c']
What is the most "pythonic" way of doing this, preferably without loops?
>Solution :
One way is to create a mapping from partition to colors, sort it; then get the values:
d = {k:v for s, v in zip(partition, colors) for k in s}
out = [d[k] for k in sorted(d)]
Output:
['r', 'b', 'r', 'c', 'b', 'c', 'b', 'c']