I have two lists, the first one contains peoples' names, with each person associated with various characters, for example numbers, letters, e.g.:
listNameAge = ['alain_90xx', 'fred_10y', 'george_50', 'julia_10l','alain_10_aa', 'fred_90', 'julia_50', 'george_10s', 'alain_50', 'fred_50', 'julia_90']
The second one contains the name of the person:
listName = ['fred', 'julia', 'alain', 'george']
Using the second list, I would like to associate a third list to the first one, such that each name in the first list is associated with its index position in the second one, i.e.:
thirdlist = [2, 0, 3, 1, 2, 0, 1, 3, 2, 0, 1]
The name and characters are separated by an underscore, but the character can be of any sort. I could loop over the elements of listNameAge
, separate the name of the persons from the rest of the characters using a .split('_')
on the string, find which name it is and find its index in listName
using a second loop.
I was however wondering if there is a simpler way to do this, i.e. avoid using loop and use only a comprehension list?
While you can do this with a one-liner, I think that, for efficiency, it wold pay to build a dictionary:
namePos = dict((name, i) for (i, name) in enumerate(listName))
>>> [namePos[n.split('_')[0]] for n in listNameAge]
[2, 0, 3, 1, 2, 0, 1, 3, 2, 0, 1]
The (expected) running time of this code, is Θ(m + n) where m is the length of the first list, and n the length of the other one.
For this question in specific, I would recommend you use a loop just for clarity. However, if you must use a list comprehension, you can do that essentially the same way:
thirdlist = [listName.index(x[:x.find('_')]) for x in listNameAge]
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