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?
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.
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.
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.
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.
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]
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])
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