我正在尝试创建一个 secret 编码程序,但在使用 for 循环时遇到了麻烦(我从未真正理解它们)。这是我到目前为止要做的,我正在尝试让用户输入,将用户文本的每个单词转换为编码文本,所以如果有人输入“hello”,它将变成“vpyyl”。有人可以帮忙吗?这可能吗?
这就是我目前所拥有的,它给出了一个错误“列表索引必须是整数,而不是 str”。我很确定 for 循环也设置错误。
import random
list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
codedList = ['s', 'q', 'n', 'z', 'p', 'o', 'k', 'v', 'm', 'c', 'i', 'y', 'w', 'a', 'l', 't', 'd', 'r', 'j', 'b', 'f', 'e', 'h', 'u', 'x', 'g']
text = input("Enter your text: ")
for i in [text]:
i = codedList[i]
print[i]
最佳答案
[text]
中只有一项:用户输入的整个字符串。您可能需要 for i in text:
,这会将 i
设置为字符串的每个字符。
此外,您已将列表命名为 list
(这意味着您已失去对内置名称 list
的访问权限)。当您尝试使用字符串访问元素时,列表由整数索引。您可能想为此使用字典,将每个字母映射到其编码的等价物。
其他几个问题是您没有任何代码来处理输入非字母(空格、标点符号)且字母全部为小写的情况。最后,您在 print
调用中使用方括号而不是圆括号,并且您没有禁止换行。
所以:
code = dict(a='s', b='q', c='n', d='z', e='p', f='o', g='k', h='v', i='m', j='c',
k='i', l='y', m='w', n='a', o='l', p='t', q='d', r='r', s='j', t='b',
u='f', v='e', w='h', x='u', y='x', z='g')
# another way to define the dictionary (you don't need both)
alphabet = "abcdefghijklmnopqrstuvwxyz"
codedalphabet = "sqnzpokvmciywaltdrjbfehuxg"
code = dict(zip(alphabet, codedalphabet))
# add upper-case versions of all letters to dictionary
for letter, codedletter in code.iteritems():
code[letter.upper()] = codedletter.upper()
for char in input("Enter your text: "):
if char in code:
print(code[char], end="")
else:
print(char, end="") # not an alphabetic character, print as-is
print() # we haven't printed a line break; do so now
正如其他人所指出的,Python 中内置了一些东西可以使这变得微不足道,但是如果您在使用 for
循环时遇到问题,那将无助于您的学习。 :-)
关于python - 无法弄清楚循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12084677/