我有以下两个python列表。
prob_tokens = ['119', '120', '123', '1234', '12345']
complete_tokens = ['112', '120', '121', '123', '1233', '1234', '1235', '12345']
min_len_sec_list = 3
max_len_sec_list = 5
我想创建一个字典,将第一个列表中的元素作为键并具有以下约束:
False
。False
。例如:
(ⅰ),而检查123
,如果1234
,12345
存在(123*
)在第二列表然后值123
将是False
。
(ii)。同样,在检查时1234
,如果12345
存在(1234*
),则值将为False
。
这*
会[0-9]{(max_len-len_token)}
True
。输出:
final_token_dict
{'119': False,'120': True, '123': False, '1234': False, '12345': True}
我可以获取有关如何实现此目标的任何建议吗?提前致谢!!!
您可以将自定义函数与字典理解一起使用:
prob_tokens = ['119', '120', '123', '1234', '12345']
complete_tokens = ['112', '120', '121', '123', '1233', '1234', '1235', '12345']
def mapper(val, ref_list):
if any(x.startswith(val) and (len(x) > len(val)) for x in ref_list):
return False
if val in ref_list:
return True
return False
res = {i: mapper(i, complete_tokens) for i in prob_tokens}
print(res)
{'119': False, '120': True, '123': False, '1234': False, '12345': True}
如果字符数标准对您很重要,则可以使用链式比较和其他输入来相应地调整逻辑:
def mapper(val, ref_list, max_len):
if any(x.startswith(val) and (0 < (len(x) - len(val)) <= max_len) for x in ref_list):
return False
if val in ref_list:
return True
return False
min_len_sec_list = 3
max_len_sec_list = 5
add_lens = max_len_sec_list - min_len_sec_list
res = {i: mapper(i, complete_tokens, add_lens) for i in prob_tokens}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句