在Python中存储整数列表
我需要创建一个可以存储整数的Python列表。然后,我需要能够使用在Python中存储整数列表,python,list,Python,List,我需要创建一个可以存储整数的Python列表。然后,我需要能够使用print()打印出每个整数,然后清空列表 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
print()
打印出每个整数,然后清空列表
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=[]
都会创建一个空列表
有关列表中的函数:请参见
针对:
将在L
的索引上循环,并打印每个索引处的值。与Java类似,Python也使用基于0的索引(因此
L[0]
是L
中的第一个元素)为了完成循环(以及简化未来问题),L[i]
访问i
th元素(0-索引),len(L)
获取元素的长度/数量,如果L:
其中L
是一个列表,计算结果为False
如果L
为空,True
则为空。不要使用range(len(L))
在列表上循环,使用作为i,elem in enumerate(L)
@DanielPryden:虽然我同意,但我不想对初学者抛出enumerate
。我只是想说明一下,你可能应该把你的后续问题作为一个新问题来问。但是“拆分”整数是什么意思呢?整数没有逗号,只有字符串表示形式有。我想打印列表中的每个整数,不是一次打印一个,而是全部打印在一个字符串中,用逗号分隔。所以,我想把我的_列表=[5,2,4],然后逐字打印出“5,2,4”
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
for i in range(len(L)):
print(L[i])