【问题标题】:Creating serial number based on occurrences in string list and then pairing根据字符串列表中的出现创建序列号,然后配对
【发布时间】:2017-07-24 09:09:17
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你试过什么?你遇到了什么错误?

标签: python list find-occurrences


【解决方案1】:

你可以使用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 返回该项目的下一个计数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    相关资源
    最近更新 更多