简体   繁体   English

在while循环后如何创建列表

[英]how to create a list after a while loop

I have a question about how to create a list after the while loop. 我有一个关于在while循环后如何创建列表的问题。 I want to put all the numbers I get from while loop into a list for example: 我想将从while循环中获得的所有数字放入一个列表中,例如:

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

then I get 然后我得到

4
5
6
7

I want to show these numbers in one list. 我想在一个列表中显示这些数字。

l=[]
x=4

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

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

print(l)

That's how you'd add it to your code. 这就是将其添加到代码中的方式。 FYI, if you want to do it the "Pythonic" way, it's as simple as: 仅供参考,如果您想以“ Pythonic”的方式进行操作,则非常简单:

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

You are looking for the append() function. 您正在寻找append()函数。 Check out the python lists document here for more information. 在此处查看python列表文档以获取更多信息。

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

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

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