Sort and filter the list based on items from the second list

I have two lists, the first one contains the names of people, and each person is associated with various symbols, for example, numbers, letters, for example:

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 contains the name of the person:

listName = ['fred', 'julia', 'alain', 'george']

Using the second list, I would like to associate the third list with the first, so that each name in the first list is associated with its index position in the second, that is:

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 type. I could cycle through the elements listNameAge, separate the names of the faces from the rest of the characters using .split('_')in a string, find the name and find its index in listName, using the second loop.

I was wondering if there is an easier way to do this, i.e. avoid using a loop and use only a list of concepts?

+4
6

listNameAge, split '_', , index, .

>>> [listName.index(i.split('_')[0]) for i in listNameAge]
[2, 0, 3, 1, 2, 0, 1, 3, 2, 0, 1]
+1

, , :

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]

: & theta; (m + n), m - , n - .

+3

, , . , , , , :

thirdlist = [listName.index(x[:x.find('_')]) for x in listNameAge]
+2

, , listNameAge listName:

for x in listNameAge:
    for y in listName:
        if y in x:
            thirdList.append(listName.index(y))

:

[2, 0, 3, 1, 2, 0, 1, 3, 2, 0, 1]
+2
thirdList = [listName.index(string.split("_")[0]) for string in listNameAge]

, listName.index(string.split("_")[0], string listNameAge. string.split("_")[0] - , listName.index(string.split("_")[0] listName.

+1

.index(), O(n) O(mn), m n .

:

map(lambda (x,y): y[x[:x.find('_')]],izip(listNameAge, repeat(dict(izip(listName, count())))))

( ):

nameMap = dict(izip(listName, xrange(len(listName))))
thirdList = map(lambda x: nameMap[x[:x.find('_')]],listNameAge)
+1

Source: https://habr.com/ru/post/1629812/


All Articles