簡體   English   中英

(PYTHON) 遍歷字典

[英](PYTHON) iterating through a dictionary

假設我有兩個字典:

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}

我希望我的“for 循環”遍歷字典並用“corLetters”鍵替換“隨機字母”鍵並輸出到一個字符串。 這是我到目前為止的方式:

for k in randomLetters.values():
    attempt = strOne.replace(randomLetters.keys()[k], corLetters.keys()[k]) 
print("\nThe first attempt at deciphering is: ")
print(attempt)

當我打印出來時,我希望輸出是“the”,但我得到的是“jpe”。 有人可以告訴我如何使用 for 循環正確迭代並將其作為字符串輸出到終端嗎?

如果您只想知道輸出:

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}
attempt=" "
for h,k in randomLetters.items():
        for i,x in corLetters.items():
            if k==x:
                attempt=attempt+i

print("\nThe first attempt at deciphering is: "+attempt)

輸出是:

但是,如果您還想更改 randomLetters 上的鍵:

randomLetters = {'j': 0, 'p': 1, 'x': 2}
corLetters = {'t': 0, 'h': 1, 'e': 2}
attempt=" "
for h,k in randomLetters.items():
        for i,x in corLetters.items():
            if k==x:
                randomLetters[i] = randomLetters.pop(h)
                attempt=attempt+i

print("\nThe first attempt at deciphering is: "+attempt)

輸出為:“the”,randomLetter 字典為“{'t': 0, 'h': 1, 'e': 2}”

希望能幫到你,祝你有美好的一天

大衛

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM