簡體   English   中英

如何將用戶輸入保存到列表Python

[英]How to save user inputs into a list python

我是python的新手。 我正在嘗試制作一個解碼游戲,讓玩家可以猜出編碼字。 我設法詢問用戶他們要替換哪個符號以及要替換為哪個字母。 但是,下次他們替換符號時,不會顯示以前的替換。 我知道我需要將用戶輸入保存到我創建的列表中,但是我不確定如何。 我想知道是否有人可以告訴我我該怎么做。 這是我的代碼:

subs2=[] # my list that i want to save the user inputs to 
while True:
    addpair1=input("Enter a symbol you would like to replace:") 
    addpair2=input("What letter would you like to replace it with:")

    for word in words_list:
        tempword = (word)
        tempword = tempword.replace('#','A')
        tempword = tempword.replace('*', 'M')
        tempword = tempword.replace('%', 'N')
        tempword=tempword.replace(addpair1,addpair2)
        print(tempword)
        subs2.append(tempword)

這是運行此命令時發生的情況:

A+/084&" (the coded words)
A3MANA+
8N203:
Enter a symbol you would like to replace:+
What letter would you like to replace it with:k
Ak/084&"
A3MANAk   (the first substitution)
8N203:
Enter a symbol you would like to replace:J
What letter would you like to replace it with:/
A+/084&"
A3MANA+   ( the 2nd one)
8N203:
Enter a symbol you would like to replace:

如您所見,以前的替換不會保存。 我在網上看了一下,但是我嘗試了一下卻沒用。 如果有人可以幫助我,我將不勝感激

輸入后,將剛剛輸入的對保存在subs2列表中:

subs2.append((addpair1, addpair2))

然后在循環中,您現在只需執行

tempword=tempword.replace(addpair1,addpair2)

而是做一個輔助循環:

for ap1, ap2 in subs2:
    tempword=tempword.replace(ap1,ap2)

並在循環結束時丟失其他append

這應該可以,但是對於許多替換來說效率不高,因為您多次復制了tempword較小變體。 如果每個addpair1都是單個字符,則將tempword轉換為可變序列(字符列表)會更快,使用dict進行替換。

因此,如果該條件確實成立,我將編寫代碼,而不是...:

subs2 = {'#':'A', '*':'M', '%':'N'}
while True:
    while True:
        addpair1=input("Enter a symbol you would like to replace:") 
        if len(addpair1) != 1:
            print('Just one character please, not {}'.format(len(addpair1)))
            continue
        if addpair1 in subs2:
            print('Symbol {} already being replaced, pick another'.format(addpair1))
            continue
        break
    addpair2=input("What letter would you like to replace it with:")
    subs2[addpair1] = addpair2

for word in words_list:
    tempword = list(word)
    for i, c in enumerate(tempword):
        tempword[i] = subs2.get(c, tempword[i])
    tempword = ''.join(tempword)
    print(tempword)

在多次替換的情況下,語義與原始代碼並不相同,但是在這種情況下,它們可能會根據您所需的確切規范為您正確解決。

暫無
暫無

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

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