以 3 为一组打印可能的子字符串并与 python 中的字典键匹配

Printing possible substring in set of 3 and matching with dictionary keys in python

我想打印 3 组中可能的子字符串,如果模式与 dictionary.keys() 匹配则分配字典值并将它们存储到新字典

input:
dict1={'000': 0, '001': 0, '010': 0, '011': 0, '100': 1, '101': 0, '110': 1, '111': 0}
str1=['010110100']

output:
sub_string= [010,101,011...]
new dict= {'010':0, '101':0, '011':0, '110':1......}

试试这个:

[str1[0][i:i+3] for i in range(len(str1[0])-2) if str1[0][i:i+3] in dict1]
{str1[0][i:i+3] : dict1.get(str1[0][i:i+3]) for i in range(len(str1[0])-2) if str1[0][i:i+3] in dict1}

# ['010', '101', '011', '110', '101', '010', '100']
# {'010': 0, '101': 0, '011': 0, '110': 1, '100': 1}

你可以这样做:

dict1={'000': 0, '001': 0, '010': 0, '011': 0, '100': 1, '101': 0, '110': 1, '111': 0}
str1= '010110100'

sub_string = []
d = {}

for i in range(len(str1)-2):
    temp = str1[i:i+3]
    sub_string.append(temp)
    d[temp] = dict1.get(temp)


print(sub_string)
print(d)
['010', '101', '011', '110', '101', '010', '100']
{'010': 0, '101': 0, '011': 0, '110': 1, '100': 1}