【问题标题】:How to add labels to strings with letters in python list?如何在python列表中为带有字母的字符串添加标签?
【发布时间】:2021-04-21 15:49:30
【问题描述】:

我写了一些运行良好的代码,但我想让它更精确。

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

['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)

【问题讨论】:

  • 如果您的代码有效,但您想查看替代解决方案,那么Code Review Stack Exchange 可能是更好的选择。我也没有投反对票。
  • 谢谢@JustinEzequiel,我不知道这个社区,以后会问!

标签: python string unique


【解决方案1】:
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”)时才有效。

【讨论】:

  • 谢谢!是的,这个限制是已知的^^
【解决方案2】:

如果你想要简洁但有点不透明,这里是一个(不可否认的半开玩笑)版本:

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']

【讨论】:

  • 谢谢,我只是想在这种情况下限制依赖,但这个模块似乎非常有用!
  • 当然,除了标准库没有依赖...
【解决方案3】:

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

这是一种更清晰的方法,同时迭代 ancestrals 列表而不是就地修改它。每个项目使用的最后一个字母的序号存储在last_letters 字典中。对于每个item,都会对其进行检查并使用下一个字母。默认值是a` 反引号)之前的任何内容,因此当向其添加 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']

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 2021-11-10
    • 2013-03-01
    • 2018-08-04
    • 2020-06-02
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    相关资源
    最近更新 更多