1 回答

TA贡献1829条经验 获得超7个赞
您得到是因为您为 中的每个循环重新分配了单个值。然后,替换 会给出错误的输出,因为您在每个循环中打印。len(protlist) = 1protlistfor x,y in diction.items()protlist = [y]protlist.append(y)protlist
但是,要开始,不应是 的长度。元组的长度是 ,但每个循环中有三个字符,然后转到接下来的三个字符。因此,您需要迭代才能到达字符串的末尾。Lentuple1170tu1170 / 3 = 390
然后有很多方法可以解决您的问题。像您提到的具有列表和联接的示例是在循环中附加值,然后在循环外部进行打印和计数。
protlist = []
for i in range(0, int(len(tuple) / 3)):
tu = tuple[3*i:3*i+3]
if tu in diction:
for x, y in diction.items():
if tu == x:
protlist.append(y)
break
print(' '.join(protlist)) #prints list items separated by a space
print(len(protlist))
我根据你的预期输出进行了测试,它给了我确切的结果。
编辑:此问题的类似简化版本的列表理解示例:
string = 'aaabbbcccdddeee'
dictionary = {'aaa': 'A', 'bbb': 'B', 'ccc': 'C', 'ddd': 'D', 'eee': 'E'}
parts = [ string[i:i+3] for i in range(0, len(string), 3) ]
output = [ dictionary[x] for x in parts if x in dictionary.keys() ]
print(' '.join(output))
添加回答
举报