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

PHPz
Release: 2024-02-08 20:57:04
forward
447 people have browsed it

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'\]
Copy after login

How do we label them so that the output is:

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

(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'\]
Copy after login

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]}')
Copy after login

If you can use :

import pandas as pd

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

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!