Given a list
[0,1,2,3,4,5,6,7,8,9,10,11,12,13]
I would like to label at each of the list position as below
['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou', 'fou', 'fou', 'thr', 'sec', 'fou']
with respect to a lookup dictionary m
m={ "fir": [0,1,3,4,5],
"sec": [2,7,12],
"thr": [6,11],
"fou": [8,9,10,13]}
Let take for example the first three position.
From the dict m
, the position 0
and 1
fell under the key fir
. Whereas, the third position (e.g., 2) is under the key sec
.
Hence, the list for the three are ['fir', 'fir', 'sec'].
To achieve the above objective, the following is drafted
m={ "fir": [0,1,3,4,5],
"sec": [2,7,12],
"thr": [6,11],
"fou": [8,9,10,13]}
all_key=m.keys()
all_opt=[]
for idx in range (sum(len(v) for v in m.values())):
for nkey in all_key:
if idx in m[nkey]:
all_opt.append(nkey)
break
which produced
opt=['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou', 'fou', 'fou', 'thr', 'sec', 'fou']
I wonder whether there is better alternative than the nested for-loop?
CodePudding user response:
You can invert the mapping dictionary so that mapping would be:
valuei ⟶ labelj
instead oflabel ⟶ [value0...valuen]
You can invert the dictionary using dict comprehension
inv_m = {v: k for k, lst in m.items() for v in lst}
print(inv_m)
# {0: 'fir', 1: 'fir', 3: 'fir', 4: 'fir', 5: 'fir', 2: 'sec',
# 7: 'sec', 12: 'sec', 6: 'thr', 11: 'thr', 8: 'fou', 9: 'fou',
# 10: 'fou', 13: 'fou'}
Now, iterate over the given list and map each value to its corresponding label.
lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
out = [inv_m[v] for v in lst]
print(out)
# ['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou',
# 'fou', 'fou', 'thr', 'sec', 'fou']
CodePudding user response:
Create a fixed size list and fill it by putting labels to corresponding indexes:
lst = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
m = {
"fir": [0,1,3,4,5],
"sec": [2,7,12],
"thr": [6,11],
"fou": [8,9,10,13]
}
label_lst = [''] * len(lst)
for label, idxs in m.items():
for idx in idxs:
label_lst[idx] = label
print(label_lst)
Output
['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou', 'fou', 'fou', 'thr', 'sec', 'fou']