我写了一些代码,工作得很好,但我想让它更精确
其想法是添加一个字母,显示列表中元素的出现情况。初始列表如下所示
['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)
当然,只有当每个元素的最大计数为26(字母“z”)时,这才有效
如果你想要简洁但有点不透明,以下是aa(无可否认是开玩笑的)版本:
例如:
虽然the ^{} solution 很好,但正如@PierreD所说,它非常不透明
这里有一种更清晰的方法,可以在
ancestrals
列表上进行迭代,而不是就地修改它。用于每个项目的最后一个字母的序号存储在last_letters
字典中。对于每个item
,都会检查它并使用下一个字母。默认值为a
(`
backtick)之前的值,因此当向其添加1时,将获得“a”相关问题 更多 >
编程相关推荐