Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort and filter a list based on elements from a second list

Tags:

python

list

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?

like image 731
gregory Avatar asked Jan 06 '23 14:01

gregory


2 Answers

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.

like image 148
Ami Tavory Avatar answered Jan 09 '23 04:01

Ami Tavory


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]
like image 29
Eric Zhang Avatar answered Jan 09 '23 03:01

Eric Zhang