Eyal Solomon
Eyal Solomon

Reputation: 618

Python number the occurrences of elements in list

Having a problem when working on lists

trying to figure out how to number elements if they appear more than once, from the second appearance i want to add the number near the '@':

for example:

['[email protected]', '[email protected]', '[email protected]','[email protected]']

wanted output :

['[email protected]', '[email protected]', '[email protected]','[email protected]']

Code so far :

count_apper=Counter(mails_list)
    for values in count_apper.items():
        for mail in mails_list:
            if values[0]==mail:
                number+=1
                temp_var=mail.split("@") 
                temp_var[0]=temp_var[0]+f"{number}"
                temp_var="@".join(temp_var)
                print(temp_var)
            number=1

Output :

[email protected]
[email protected]
[email protected]
[email protected]

Upvotes: 1

Views: 75

Answers (3)

user15801675
user15801675

Reputation:

Try this


j=['[email protected]', '[email protected]', '[email protected]','[email protected]']
count=1
k=j.copy()
for i in range(len(j)):
    
    if k.count(k[i])>1:
        m=[char for char in j[i]]
        m.insert(j[i].index('@'),str(count)
        )
        count+=1
        j[i]=''.join(m)
print (j)

Upvotes: 0

JonSG
JonSG

Reputation: 13067

I would base my answer off of a collections.Counter() I think. It will do some of the work for you.

import collections

addresses = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']

results = []

for address, count in collections.Counter(addresses).items():
    # add a "first" address as is
    results.append(address)

    # If there were other occurrences add them
    for i in range(1, count):
        results.append(f"{i+1}@".join(address.split("@")))

print(results)

This should give you:

['[email protected]', '[email protected]', '[email protected]', '[email protected]']

Upvotes: 2

H. Rittich
H. Rittich

Reputation: 845

You can iterate the list and use a dict to keep track of the number of occurences of a specific address. To add text before the @ sign, you can use the .split method of str. A possible implementation looks as follows.

addresses = ['[email protected]', '[email protected]', '[email protected]', '[email protected]']
occurence_count = {}
transformed = []
for a in addresses:
    count = occurence_count.get(a, 0) + 1
    occurence_count[a] = count

    name, domain = a.split('@')
    if count > 1:
        transformed.append(f'{name}{count}@{domain}')
    else:
        transformed.append(a)

print(transformed) 

Upvotes: 0

Related Questions