根据字符串列表中的出现创建序列号,然后配对

Creating serial number based on occurrences in string list and then pairing

我正在尝试根据字符串列表创建标识号列表。 ID 号将是字符串和连续数字的组合。

我的输入列表的简短示例:

['N10','N10','N20','N30','N40','N40','N40','N40','N40','N20']

然后我想根据名字+一个连续的数字生成一个新的列表,这个列表不能有重复。像这样:

['N100','N101','N200','N300','N400','N401','N402','N403','N404','N201']

您可以使用 collections.Counter:

In [38]: import collections 

In [39]: c = collections.Counter(l) # l is your data

创建唯一的查找 <item: iter(range(count[item]))>:

In [44]: lookup = {x : iter(range(c[x])) for x in set(l)} 

使用 list comp return 该项目的下一个计数:

In [45]: [x + str(next(lookup[x])) for x in l]
Out[45]: 
['N100',
 'N101',
 'N200',
 'N300',
 'N400',
 'N401',
 'N402',
 'N403',
 'N404',
 'N201']