Python列表重复项编号更新:无Numpy实现方案需求
列表重复元素的编号处理
我们有如下两个示例列表:
lista = ['facility', 'resource', 'resource', 'resource', 'facility', 'other', 'resource', 'resource'] listb = ['facility', 'resource', 'other', 'another']
需要编写函数对其进行处理,核心要求为:对lista中重复出现的元素添加编号(仅针对在listb中存在的元素),listb保持原状态不变。
要求的处理结果
基础处理结果:
lista_new = ['facility', 'resource', 'resource1', 'resource2', 'facility1', 'other', 'resource3', 'resource4'] listb_new = ['facility', 'resource', 'other', 'another']
更理想的处理结果(优先实现,且不使用Numpy库):
lista_new = ['facility0', 'resource0', 'resource1', 'resource2', 'facility1', 'other', 'resource3', 'resource4'] listb_new = ['facility', 'resource', 'other', 'another']
实现方案
思路
通过字典动态记录每个目标元素的当前编号,遍历lista时:
- 对存在于
listb中的元素,按出现顺序添加递增编号; - 不存在于
listb中的元素直接保留原样; listb直接返回副本,不做修改。
代码实现
def process_lists(lista, listb): # 记录每个元素当前的编号 current_index = {} lista_new = [] for item in lista: if item in listb: # 初始化元素的起始编号为0 current_index.setdefault(item, 0) # 生成带编号的新元素(对应更理想的结果) new_item = f"{item}{current_index[item]}" # 如果需要基础处理结果,替换为以下代码块: # if current_index[item] == 0: # new_item = item # else: # new_item = f"{item}{current_index[item]}" lista_new.append(new_item) current_index[item] += 1 else: lista_new.append(item) # 返回处理后的lista和原状态的listb副本 return lista_new, listb.copy() # 测试示例 lista = ['facility', 'resource', 'resource', 'resource', 'facility', 'other', 'resource', 'resource'] listb = ['facility', 'resource', 'other', 'another'] lista_new, listb_new = process_lists(lista, listb) print(lista_new) print(listb_new)
代码说明
- 用
current_index字典动态追踪每个元素的编号,遍历到目标元素时自动递增编号,确保顺序对应; - 注释部分提供了基础处理结果的切换方式,只需替换对应代码块即可;
- 对
listb返回副本,避免原列表被意外修改。
内容的提问来源于stack exchange,提问作者geofisue
相关产品推荐
相关产品推荐

