Home  >  Article  >  Backend Development  >  Mark a list by the unique elements that appear in the list

Mark a list by the unique elements that appear in the list

PHPz
PHPzforward
2024-02-08 20:57:04449browse

Mark a list by the unique elements that appear in the list

Question content

Given a list of strings, for example:

foo = \['a', 'a', 'b', 'a', 'b', 'c', 'c', 'a', 'b', 'c', 'a'\]

How do we label them so that the output is:

output = \['a1', 'a2', 'b1', 'a3', 'b2', 'c1', 'c2', 'a4', 'b2', 'c3', 'a5'\]

(Keep the original list order)

In the following case, there are only 3 unique variables to look at, so my first thought is to look at the unique elements:

import numpy as np

np.unique(foo)

Output = \['A', 'B', 'C'\]

But I get stuck when I try to find the right loop to achieve the desired output.


Correct answer


Use pure python and use a dictionary to calculate the value:

foo = ['a', 'a', 'b', 'a', 'b', 'c', 'c', 'a', 'b', 'c', 'a']

d = {}
out = []
for val in foo:
    d[val] = d.get(val, 0)+1
    out.append(f'{val}{d[val]}')

If you can use :

import pandas as pd

s = pd.Series(foo)
out = s.add(s.groupby(s).cumcount().add(1).astype(str)).tolist()

Output: ['a1', 'a2', 'b1', 'a3', 'b2', 'c1', 'c2', 'a4', 'b3', 'c3', ' a5' ]

The above is the detailed content of Mark a list by the unique elements that appear in the list. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete