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?
CodePudding user response:
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']
CodePudding user response:
I would personally go for this approach (it does involve for loops, but uses zip which is quite Pythonic):
n = 8
partitions = [{0,2},{1,4,6},{3,5,7}]
colors = ['r','b','c']
result = [''] * n # or result = [None] * n
for color, partition in zip(colors, partitions):
for index in partition:
result[index] = color
print(result) # prints ['r', 'b', 'r', 'c', 'b', 'c', 'b', 'c']
