将我的整数放入python中的列表中

时间:2012-11-07 16:07:34

标签: python string list char ord

我正在创建一个使用Caesar密码对消息进行编码和解码的程序。到目前为止,我正在构建基础工作,我正在尝试获取用户给我的字符列表并使用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

输入(“Hello,Party people!”) 产量 它将它们全部打印在单独的线条上,方括号围绕它们...任何想法?

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

4 个答案:

答案 0 :(得分:4)

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

user_numbers_list = [ord(letter) for letter in user_words_refined]

答案 1 :(得分: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对于更简洁方法的回答

答案 2 :(得分: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)

答案 3 :(得分: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()

因此您不必在if语句中使用太多or