I have 2 different lists:
l1 = ['a','b','a','e','b','c','a','d']
l2 = ['t1','t2','t3','t4','t5','t6','t7','t8']
The lengths of l1 and l2 will always be the same. They're in fact logical mappings - each item in l1 corresponds to a value in l2.
I wanted to identify distinct elements in l1. I did that using set and list comprehension as follows:
used = set()
distl1 = [x for x in l1 if x not in used and (used.add(x) or True)]
Here, the output will be:
distl1 = ['a','b','e','c','d']
which is nothing but the first occurrence of every distinct element.
Now, how do I build a list distl2 so that I get the output as the value in l2 that corresponds to the first occurrence's value i.e., distl1?
distl2 = ['t1','t2','t4','t6','t8']
My idea is to use an OrderedDict to build a mapping of (key, value) pairs corresponding to the elements of l1 and l2 and then extract the values from that dict as a list.
>>> from collections import OrderedDict
>>>
>>> l1 = ['a','b','a','e','d','c','a','b']
>>> l2 = ['t1','t2','t3','t4','t5','t6','t7','t8']
>>>
>>> d = OrderedDict()
>>> for k, v in zip(l1, l2):
...: if k not in d: # <--- check if this key has already been seen!
...: d[k] = v
...:
>>> distl2 = list(d.values())
>>> distl2
>>> ['t1', 't2', 't4', 't5', 't6']
Note for Python 3.7+ users: regular dicts are guaranteed to remember their key insertion order, so you can omit importing the OrderedDict.
You can also do this:
distl2 = [l2[l1.index(key)] for key in distl1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With