繁体   English   中英

在 Python 中存储整数列表

[英]Store a List of Integers in Python

我需要创建一个可以存储整数的 Python 列表。 然后我需要能够使用print()打印出每个整数,然后清空列表。

In [35]: L = [] # create empty list

In [36]: L.append(1)

In [37]: L.append(2) # this could go on for a while

In [38]: L
Out[38]: [1, 2]

In [39]: print(L)
[1, 2]

In [40]: for num in L:
   ....:     print(num)
   ....:     
1
2

In [41]: L = []  # clear the list

回应@jedward 的评论

for i in range(len(L)):
    print(L[i])

将遍历L的索引,并在每个索引处打印值。
类似于使用Java,Python还使用基于0的索引(所以L[0]是在所述第一元件L

the_list=[] # create list
the_list.append(1) # add number
for x in the_list:
    print(x) # print number
the_list=[] # clear list

如果您有很多整数,则可以执行以下操作:

a=open("file","r") # if they're in a file and written newline-separated
for x in a:
    the_list.append(int(x)) # add a value to list
a.close() # close file
for x in the_list:
    print(x) # print value line by line
the_list=list() # empty list

l = list() , l = []都创建一个空列表。

有关列表中的函数:请参阅https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types

暂无
暂无

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

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