Python为列表中出现的元素编号

2024-05-06 06:42:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在处理列表时遇到问题

试图找出如果元素出现多次,如何对其编号,从第二次出现开始,我想在“@”附近添加数字:

例如:

['example@company.com', 'example@company.com', 'none@comapny.com','example@company.com']

想要的输出:

['example@company.com', 'example2@company.com', 'none@comapny.com','example3@company.com']

迄今为止的代码:

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

输出:

example1@company.com
example2@company.com
example2@company.com
none2@company.com

Tags: comnonenumberforexamplevarcountmail
3条回答

您可以迭代列表并使用dict来跟踪特定地址的出现次数。要在@符号之前添加文本,可以使用str.split方法。可能的实现如下所示

addresses = ['example@company.com', 'example@company.com', 'none@comapny.com', 'example@company.com']
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) 

试试这个


j=['example@company.com', 'example@company.com', 'none@comapny.com','example@company.com']
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)

我想我的答案是基于一个collections.Counter()的。它将为你做一些工作

import collections

addresses = ['example@company.com', 'example@company.com', 'none@comapny.com', 'example@company.com']

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)

这应该给你:

['example@company.com', 'example2@company.com', 'example3@company.com', 'none@comapny.com']

相关问题 更多 >