Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a list of strings to a list of integers [duplicate]

Tags:

python

I have a list with n elements:

['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai', 'rpe']

I have to assign a number to each string, zero at the start, and then increment by one if the element is different, instead give the same number if the element repeats. Example:

['pea', 'rpai', 'rpai', 'schiai', 'pea', 'rpe', 'zoi', 'zoi', 'briai', 'rpe']
[ 0,    1,      1,      2,        0,     3,     4,     4,     5,       3    ]

How can I do it?

like image 591
lola Avatar asked Nov 14 '20 20:11

lola


People also ask

How do I map a list to another list in Python?

The map() function iterates over all elements in a list (or a tuple), applies a function to each and returns a new iterator of the new elements. In this syntax, fn is the name of the function that will call on each element of the list. In fact, you can pass any iterable to the map() function, not just a list or tuple.

How to append list to another list in java?

It is possible to add all elements from one Java List into another List . You do so using the List addAll() method. The resulting List is the union of the two lists.

How do I convert a string to an integer in Python?

To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. Use the syntax print(int("STR")) to return the str as an int , or integer.

How do you map a string to a list in Python?

We can also use the map() function to convert a list of strings to a list of numbers representing the length of each string element i.e. It iterates over the list of string and apply len() function on each string element. Then stores the length returned by len() in a new sequence for every element.


2 Answers

With a helper dict:

>>> [*map({k: v for v, k in enumerate(dict.fromkeys(final))}.get, final)]
[0, 1, 1, 2, 0, 3, 4, 4, 5, 3]

Another way:

>>> d = {}
>>> [d.setdefault(x, len(d)) for x in final]
[0, 1, 1, 2, 0, 3, 4, 4, 5, 3]
like image 147
superb rain Avatar answered Oct 22 '22 16:10

superb rain


using a dictionary would achieve this.

def counts(a):
    dis = {}
    count=0
    for i in range(len(a)):
        if a[i] not in dis.keys():
            dis[a[i]] = count
            count+=1
        
    return([dis[x] for x in a])
like image 22
algorythms Avatar answered Oct 22 '22 16:10

algorythms