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))
添加回答
舉報