Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add number to the strings in the list in python

Tags:

python

I want to add numbers to list of strings so I can keep count of number of items.

Assume I have a list like this:

list = ['a', 'b', 'A', 'b', 'a', 'C', 'D', 'd']

I want to assign a number to each string irrespective of capital or small letters, Here's the output I'm looking for,

list = ['a_1', 'b_1', 'A_2', 'b_2', 'a_3', 'C_1', 'D_1', 'd_2']

This is what I've tried but I'm not getting the correct output

list = [j+f'_{i}' for i, j in enumerate(lst, 1)]
like image 683
user_12 Avatar asked Jan 27 '23 01:01

user_12


1 Answers

You can keep track of how many times you have seen a number in a dictionary, and update the count whenever you see the letter, and use the last count to append to the character.

from collections import defaultdict

def label(lst):

    dct = defaultdict(int)
    output = []

    #Iterate through the list
    for item in lst:

        char = item.lower()
        #Update dictionary
        dct[char] += 1

        #Create the list of characters with count appended
        output.append(f'{item}_{dct[char]}')

    return output

print(label(['a', 'b', 'A', 'b', 'a', 'C', 'D', 'd']))

The output will be

['a_1', 'b_1', 'A_2', 'b_2', 'a_3', 'C_1', 'D_1', 'd_2']

Also don't use list as a variable name, since it's a reserved python builtin name.

like image 124
Devesh Kumar Singh Avatar answered Jan 28 '23 15:01

Devesh Kumar Singh