如何在while循环后创建列表

时间:2014-09-18 02:27:09

标签: python list while-loop

我有一个关于如何在while循环后创建列表的问题。我想将我从循环中得到的所有数字放入列表中 例如:

x=4
while(1):
    print(x)
    x=x+1
    if x==8:break

然后我得到

4
5
6
7

我想在一个列表中显示这些数字。

3 个答案:

答案 0 :(得分:2)

l=[]
x=4

while(1):
    print(x)
    l.append(x)

    x=x+1
    if x==8:break

print(l)

您将如何将其添加到代码中。仅供参考,如果你想这样做的话," Pythonic"方式,它很简单:

l = range(4, 8)

答案 1 :(得分:1)

L = []
i = 4
while i<=8:
    print(i)
    L.append(i)
    i += 1

答案 2 :(得分:1)

您正在寻找append()函数。有关详细信息,请查看python lists document here

list=[] #declare a blank list to use later
x=4

while(1):
    list.append(x) #add x to the list
    x += 1 # a shorthand way to add 1 to x
    if x == 8:break

print(list) #after the loop is finished, print the list