4 回答
TA贡献1804条经验 获得超8个赞
使用regex.
import re
pattern = '|'.join(blacklist)
[re.sub(pattern+'$', '', x) for x in sample]
输出:
['sample_A',
'sample_A',
'sample_A',
'my_long_sample_B',
'other_sample_C',
'sample_A',
'sample1_D']
TA贡献1865条经验 获得超7个赞
来吧,看看这是否符合您的要求。
基本上,您只是拆分'_'角色并测试列表中的最后一个拆分是否在您的黑名单中。如果True,则放下它,如果False将字符串重新组合在一起;并根据结果建立一个新列表。
blacklist = ['_001', '_002', '_003', '_004', '_005', '_006', '_007', '_008',
'_01', '_02', '_03', '_04', '_05', '_06', '_07', '_08', '_09',
'_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9']
sample = ['sample_A', 'sample_A_001', 'sample_A_002', 'my_long_sample_B_1',
'other_sample_C_08', 'sample_A_03', 'sample1_D_07']
results = []
for i in sample:
splt = i.split('_')
value = '_'.join(splt[:-1]) if '_{}'.format(splt[-1:][0]) in blacklist else '_'.join(splt)
results.append(value)
print(results)
输出:
['sample_A', 'sample_A', 'sample_A', 'my_long_sample_B', 'other_sample_C', 'sample_A', 'sample1_D']
TA贡献1843条经验 获得超7个赞
您可以遍历示例列表,如果元素的最后一个字符是数字,那么您可以遍历黑名单项目,检查字符串是否以该字符结尾。如果是这样,那么您可以从字符串中删除黑名单项并将结果重新分配给示例列表。
blacklist = [
'_001', '_002', '_003', '_004', '_005', '_006', '_007', '_008', '_009',
'_01', '_02', '_03', '_04', '_05', '_06', '_07', '_08', '_09',
'_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9'
]
sample = ['sample_A', 'sample_A_001', 'sample_A_002', 'my_long_sample_B_1', 'other_sample_C_08', 'sample_A_03', 'sample1_D_07']
for index, item in enumerate(sample):
#check if the last char is a digit, if its not then it cant be in our black list so no point checking
if item[-1].isdigit():
for black in blacklist:
if item.endswith(black):
sample[index] = item.rstrip(black)
print(sample)
输出
['sample_A', 'sample_A', 'sample_A', 'my_long_sample_B', 'other_sample_C', 'sample_A', 'sample1_D']
TA贡献1856条经验 获得超11个赞
您可以使用正则表达式中的sub:
import re
from functools import partial
blacklist = ['_001', '_002', '_003', '_004', '_005', '_006', '_007', '_008', '_009',
'_01', '_02', '_03', '_04', '_05', '_06', '_07', '_08', '_09',
'_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9']
def sub(match, bl=None):
if match.group() in bl:
return ""
return match.group()
repl = partial(sub, bl=set(blacklist))
sample = ['sample_A', 'sample_A_001', 'sample_A_002', 'my_long_sample_B_1', 'other_sample_C_08', 'sample_A_03',
'sample1_D_07']
print([re.sub("_[^_]+?$", repl, si) for si in sample])
输出
['sample_A', 'sample_A', 'sample_A', 'my_long_sample_B', 'other_sample_C', 'sample_A', 'sample1_D']
看看为什么这是要走的路,如果你想要速度,在这里。
添加回答
举报
