首页 > 解决方案 > 在将项目附加到列表中时查找项目的索引值

问题描述

dupes是在列表中找到的重复项的列表。 clipb是原始列表。

我现在搜索dupesin的部分字符串clipb。一天结束的目的是将单词附加"duplicate"到每个找到的重复项的原始列表中。

dupes = ['0138', '0243']
clipb = ['ABC2b_0243D_K6_LOPA-PAST', 'ABC2b_0016G_M1_LOPA-PABR', 'ABC2b_0138H_M1_LOBR-BRMU', 'ABC2b_0138G_J1_LOPA-PAST', 'ABC2b_0243A_O§_STMA-MACV']

def Filter(clipb, dupes):
    return [str for str in clipb if
            any(sub in str for sub in dupes)]
            #index = clipb.index(clipb)  <<--- no idea how to add it in here 
    
rs_found = (Filter(clipb, dupes))
print ("found dupicates from the original list are: ","\n", rs_found)

当前输出只是找到的重复项列表。从原始列表中找到的重复项是:

['ABC2b_0243D_K6_LOPA-PAST', 'ABC2b_0138H_M1_LOBR-BRMU', 'ABC2b_0138G_J1_LOPA-PAST', 'ABC2b_0243A_O§_STMA-MACV']

我的问题是我不知道如何格式化Filter以包括输出找到的重复项的索引,以便我可以实际更改项目。

标签: pythonpython-3.x

解决方案


而不是仅仅过滤掉重复项,因为你希望重复的项目tab附加了一个和“DUPLICATE”,当你找到一个重复项时就这样做,而不是把它过滤掉:

clipb = ['ABC2b_0243D_K6_LOPA-PAST', 'ABC2b_0016G_M1_LOPA-PABR', 'ABC2b_0138H_M1_LOBR-BRMU',
         'ABC2b_0138G_J1_LOPA-PAST', 'ABC2b_0243A_O§_STMA-MACV']

seen = set()
final = []
for item in clipb:
    tag = item[6:10]  # assuming tags are always at this index
    if tag in seen:
        item += '\tDUPLICATE'  # or '<space>DUPLCATE', as needed
    else:
        seen.add(tag)
    final.append(item)

print(final)
# Output:
['ABC2b_0243D_K6_LOPA-PAST',
 'ABC2b_0016G_M1_LOPA-PABR',
 'ABC2b_0138H_M1_LOBR-BRMU',
 'ABC2b_0138G_J1_LOPA-PAST\tDUPLICATE',
 'ABC2b_0243A_O§_STMA-MACV\tDUPLICATE']

请注意,您不需要预先创建重复标签的列表 - 这是在代码中完成的;模糊地改编自https://docs.python.org/3/library/itertools.htmlunique_everseen的配方。


推荐阅读