简体   繁体   English

while循环中仅将最后一项追加到列表中(Python)

[英]Only the last item is being appended to a list in a while loop (Python)

I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. 我正在尝试创建一个程序,使用while循环将输入数字的每个数字放入列表中。 However, it only appends the last digit of the number to the list. 但是,它仅将数字的最后一位附加到列表中。

Code - 代码-

num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0

while x < numlen:
    digits = []
    a = numstr[x]
    digits.append(a)
    x = x + 1

print(digits)

So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1 . 因此,如果我输入372作为数字,则列表将只是长度为1 ['2']

试试这个代码:

digits = [i for i in str(num)]

You cannot do better than digits = list(str(num)) . 您不能做得比digits = list(str(num)) In fact, since input returns a string, even the conversion to a number is not necessary: 实际上,由于input返回一个字符串,所以甚至不必转换为数字:

num = input("Enter a number: ")
digits = list(num)

(You still may want to ensure that what's typed is indeed a number, not a random string.) (您仍然可能要确保键入的确实是数字,而不是随机字符串。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM