【发布时间】:2021-12-22 16:47:28
【问题描述】:
我必须创建一个固定大小的数组,然后从数据文件中部分填充。固定大小需要为 10 并且文件中有三行。使用我当前的代码,我在数组中得到了 7 个项目,列为 ' ' 如何编辑此代码以仅部分填充数组并忽略空白点?
MAX_COLORS = 10
colors = [''] * MAX_COLORS
counter = int(0)
filename = input("Enter the name of the color file (primary.dat or secondary.dat): ")
infile = open(filename, 'r')
line = infile.readline()
while line != '' and counter < MAX_COLORS:
colors[counter] = str.rstrip(line)
counter = counter + 1
line = infile.readline()
infile.close()
【问题讨论】:
-
每次读取一行而不是设置时,使用列表然后
.append()而不是初始化。 -
@LarrytheLlama 您能否进一步澄清这一点?现在,当我打印读取的内容时,我的结果是 ['', '', '', '', '', '', '', 'blue', 'red', 'yellow']