python - 在将项目附加到列表中时查找项目的索引值
问题描述
dupes
是在列表中找到的重复项的列表。
clipb
是原始列表。
我现在搜索dupes
in的部分字符串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
以包括输出找到的重复项的索引,以便我可以实际更改项目。
解决方案
而不是仅仅过滤掉重复项,因为你希望重复的项目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
的配方。
推荐阅读
- makefile - Make:如何获得先决条件N
- python - *、in *zip 和 *D.items() 做什么?
- sql - 以更广泛的方式从确定的过滤器中提取 posgresql 中的最后一个日期和上一个日期
- python - 如何以两个为一组将 DataFrame 打印到多个 Excel 工作表?
- python - python.pythonPath 的 settings.json 环境变量在 Windows 和 Linux 之间不起作用
- powershell - PowerShell 中是否允许嵌套循环和 if 语句?
- excel - 为什么每个循环的 VBA 100,000 单元格需要这么长时间?
- c# - 如何控制 ExpressionAnimation 中的变量值?
- powershell - Powershell 将对象数组转换为 PSCustomObject
- python - 从字典中写入一个 CSV,其中值作为标题键对齐在下