How to count repetition for each value individually in Python

This is my first post, and I want to say hello to you all.

I need help counting the codes of certain items that have the same value. For example, if I have the following article codes:
Article01,
Article01,
Article01,
Article02,
Article03,
Article03.

It should look like this:
Article01_1,
Article01_2,
Article01_3,
Article02_1,
Article03_1,
Article03_2.

The data source is excel, and I already created the code pairing, but I can’t figure out how to count each code individually.

Current code:

for row in range(rbegin, rfinish):
    for col in range(1, 2):  
        char = get_column_letter(col)
        article_number = ws[char + str(row)].value
        new_article_number = article_number[:-4] 
        for subdir, dirs, files in os.walk(articles_path): 
            for folder_article in files:  
                if folder_article.__contains__(new_article_number):
                    article_found_count += 1
                    article_copy = os.path.join(subdir, folder_article)  
                    shutil.copy2(article_copy, paired_articles_path)  
                    updated_article = folder_article[:10] #because article codes from first column have 10 characters
                    print(f"{new_article_number};{updated_article}_{article_found_count}")

Thank you in advance.

  • 3

    If the posted code solves your problem, why are you here? If it does not, please details how its results differ from what you want, and what you did to try and resolve them.

    – 

  • Also give a minimum reproducible example, you don’t need to add the code for how you read the data from xl for example if there is no problem in that

    – 

  • Hi, @ScottHunter. Actually, I posted this so you can see what the pairing code looks like, but I didn’t make a counter for each code individually as I mentioned above. Thank you

    – 

  • I corrected the code, because I think the problem is in the for loop

    – 

The Counter class from collections module is likely what you are looking for. Example usage:

from collections import Counter

c = Counter()

for article in ["A1", "A2", "A2", "A1", "A3", "A1"]:
    c[article] += 1
    print(f"{article}_{c[article]}")

Output:

A1_1
A2_1
A2_2
A1_2
A3_1
A1_3

Leave a Comment