为什么我的代码不打印整个列表?

2024-04-24 21:58:43 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

import string
l=string.ascii_lowercase

the_input=list(raw_input("Enter your message to encode it: "))
for i in the_input:
    xyz=[l.find(i)+1] 
#set_alpha_num=[alphabets.index(find) for find in user_msg] 
print(xyz)

如果我输入"test",那么它只打印[20],但是我需要输出如下:[20, 5, 19, 20]


Tags: theinimport密码forinputyourstring
3条回答

您可以使用列表(Out)保存每个循环中的所有结果:

import string
l=string.ascii_lowercase
out = []
the_input=list(input("Enter your message to encode it: "))
for i in the_input:
    xyz=[l.find(i)+1] 
    out.append(xyz)
#set_alpha_num=[alphabets.index(find) for find in user_msg] 
print(out)

“测试”输出:

[20, 5, 19, 20]

正如您所要求的:

import string
l=string.ascii_lowercase
xyz=[]
the_input=list(raw_input("Enter your message to encode it: "))
for i in the_input:
    xyz +=[l.find(i)+1]
#set_alpha_num=[alphabets.index(find) for find in user_msg]
print(xyz)

您不断地重新分配xyz,所以它将是您上次分配给它的内容。你知道吗

因为你有一个列表,你想转换成一个不同的列表,我会在这里使用一个列表理解:

[l.find(i)+1 for i in the_input]
#   ^ Whatever's here is appended to a new list

相关问题 更多 >