2

我正在创建一个使用凯撒密码对消息进行编码和解码的程序。到目前为止,我正在构建基础工作,我正在尝试获取用户给我的字符列表并使用 ord 制作整数列表......到目前为止,我遇到的所有问题是将收到的整数重新放入一个列表。

import random

encode_decode = input("Do you want to encode, or decode? (e/d)")

shift_amount = input("Please enter the shift amount for your message")

if encode_decode == "e" or encode_decode == "E":
    user_words_unrefined = input("Enter your message to encode!")
elif encode_decode == "d" or encode_decode == "D":
    user_words_unrefined = input("Enter your message to decode!")

user_words_refined = list(user_words_unrefined)

Alphabet = [chr(i) for i in range(ord('a'), ord('z') + 1)]

Counter = 0
for i in range(len(user_words_refined)):
    user_words_numbers = (ord(user_words_refined[Counter]))
    user_numbers_list = [user_words_numbers]
    print(user_numbers_list)
    Counter += 1

输入(“你好,党的人!”)输出它将它们全部打印在单独的行上,并用方括号括起来......有什么想法吗?

[72]
[101]
[108]
[108]
[111]
[44]
[32]
[80]
[97]
[114]
[116]
[121]
[32]
[112]
[101]
[111]
[112]
[108]
[101]
4

4 回答 4

4

您可以使用列表推导,而不是使用跨越输入字符串长度的 for 循环。

user_numbers_list = [ord(letter) for letter in user_words_refined]
于 2012-11-07T16:14:23.337 回答
2

这应该可以解决您的问题。请参阅代码中的注释。如果需要,我很乐意提供进一步的解释

user_numbers_list = []    #initialise the list
Counter = 0
for i in range(len(user_words_refined)):
    user_words_numbers = (ord(user_words_refined[Counter]))
    user_numbers_list.append(user_words_numbers)     #add to the end of the list
    print(user_numbers_list)
    Counter += 1

最好的选择实际上是列表理解......请参阅 Jordan Lewis 的答案以获得更简洁的方法

于 2012-11-07T16:15:09.370 回答
1

将最后一部分更改为类似

user_numbers_list = []
Counter = 0
for i in range(len(user_words_refined)):
    user_words_numbers = (ord(user_words_refined[Counter]))
    user_numbers_list.append(user_words_numbers)
    print(user_numbers_list)
    Counter += 1

另外,考虑直接通过 user_words_refined 进行迭代,例如

for word in user_words_refined:
    user_words_numbers = ord(word)
    user_numbers_list.append(user_words_numbers)
    print(user_numbers_list)
于 2012-11-07T16:15:26.233 回答
0

就像旁注一样,而不是

encode_decode = input("Do you want to encode, or decode? (e/d)")

你可以使用

encode_decode = input("Do you want to encode, or decode? (e/d)").lower()

所以你不必or在你的 if 语句中使用太多的 's。

于 2012-11-07T16:25:14.177 回答