Avi*_*ton 6 python string dictionary
我有两个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
Run Code Online (Sandbox Code Playgroud)
我想创建一个字典,其中第一个列表中的元素作为键并具有以下约束:
False.False.例如:
(i)在检查时123,如果1234,12345存在(123*)在第二个列表中,那么值123将是False.
(ⅱ).同样在检查时1234,如果12345exists(1234*)则值为False.
这*将是[0-9]{(max_len-len_token)}
True.输出:
final_token_dict
{'119': False,'120': True, '123': False, '1234': False, '12345': True}
Run Code Online (Sandbox Code Playgroud)
我可以获得有关如何实现这一目标的任何建议吗?提前致谢!!!
您可以使用具有字典理解的自定义函数:
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}
Run Code Online (Sandbox Code Playgroud)
如果字符数标准对您很重要,您可以使用链式比较和其他输入相应地调整逻辑:
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}
Run Code Online (Sandbox Code Playgroud)