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

时间:2018-05-17 12:40:00

标签: 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]

4 个答案:

答案 0 :(得分:1)

这就像你问的那样有效:

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)

答案 1 :(得分:0)

您继续重新分配xyz,因此它将是您上次分配给它的任何内容。

由于您有一个列表要转换为其他列表,我在此处使用列表推导:

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

答案 2 :(得分:0)

您可以使用列表(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)

Output for“test”:

[20, 5, 19, 20]

答案 3 :(得分:0)

import string
l=string.ascii_lowercase

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

输出:

[20, 5, 19, 20]

说明:

创建一个空列表list1并将值附加到它以获得所需的输出

从你的代码:

当您将值分配给xyz时,它会在for循环的每次迭代中得到更新。所以[20]字符只有t

相关问题