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