如何在python列表中向带有字母的字符串添加标签?

2024-10-04 11:26:35 发布

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

我写了一些代码,工作得很好,但我想让它更精确

其想法是添加一个字母,显示列表中元素的出现情况。初始列表如下所示

['1','2','1','2','1']

我想要

['1a','2a','1b','2b','1c']

我确信有一个快速的答案或功能可以做到这一点,有人有想法吗?

我的代码如下:

ancestrals = ['1','2','1','2','1']
uni_a = list(set(ancestrals))
for i in range(len(ancestrals)):
    tmp = uni_a.index(ancestrals[i])
    if uni_a[tmp][-1].isalpha():
        val = ancestrals[i][:1] + chr(ord(uni_a[tmp][-1])+1)
    else:
        val = ancestrals[i] + "a"

    ancestrals[i] = val

    while uni_a[tmp] in ancestrals[i:]:
        p = ancestrals[i:].index(uni_a[tmp])+ i
        ancestrals[p] = val

    uni_a[tmp] = ancestrals[i]
print(ancestrals)

Tags: 答案代码in功能元素列表index字母
3条回答
ancestrals = ['1','2','1','2','1']

count = {}
for i, anc in enumerate(ancestrals):
    cnt = count.get(anc, 0)
    count[anc] = cnt + 1
    ancestrals[i] += chr(ord('a') + cnt)

print (ancestrals)
#  > ['1a', '2a', '1b', '2b', '1c']

当然,只有当每个元素的最大计数为26(字母“z”)时,这才有效

如果你想要简洁但有点不透明,以下是aa(无可否认是开玩笑的)版本:

from collections import Counter

def decorate(a):
    cnt = Counter()
    return [f'{x}{chr(ord("a") + i)}' for x in a for i in [cnt.update(x) or cnt[x] - 1]]

例如:

>>> decorate(['1','2','1','2','1'])
['1a', '2a', '1b', '2b', '1c']

虽然the ^{} solution很好,但正如@PierreD所说,它非常不透明

这里有一种更清晰的方法,可以在ancestrals列表上进行迭代,而不是就地修改它。用于每个项目的最后一个字母的序号存储在last_letters字典中。对于每个item,都会检查它并使用下一个字母。默认值为a`backtick)之前的值,因此当向其添加1时,将获得“a”

ancestrals = ['1','2','1','2','1']
last_letters = {}
uni_a = []  # will hold the result
default = ord('a') - 1  # char before 'a' is '`'

for item in ancestrals:
    prev_ord = last_letters.get(item, default)  # these two lines can be
    next_letter = chr(prev_ord + 1)             # combined into one
    uni_a.append(item + next_letter)
    last_letters[item] = prev_ord + 1

print(uni_a)
# ['1a', '2a', '1b', '2b', '1c']

相关问题 更多 >