【问题标题】:Looking to partially fill a fixed size array from file in python希望从 python 中的文件中部分填充固定大小的数组
【发布时间】: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']

标签: python arrays file


【解决方案1】:

作为@LarrytheLlama cmets,尝试使用append:

# you do not need str() because rstrip() return str.
colors.append(rstrip(line))

如果您不将“计数器”用于其他目的,您可能还需要删除它。

【讨论】:

  • 你好,当我尝试这样做时,我现在得到一个错误:AttributeError: 'str' object has no attribute 'append'
  • 刚刚更新了答案。
【解决方案2】:

问题出在下面一行:

colors[counter] = str.rstrip(line)

应该是:

colors[counter] = line.rstrip()

解释:您的变量linestr 类型的对象,rstripstr 的方法。调用 line.rstrip() 会返回 line 的 rstripped 副本。

编辑:根据您的 cmets,我现在了解您正在寻找什么结果。您只需从文件中读取最多 10 行或更少的行,并将值(不带换行符)放入列表中。

我冒昧地重写了您的程序,不仅是为了解决您遇到的问题,而且我还对其进行了清理和简化。我希望这段代码向您展示了其他一些对您有用的技巧。

MAX_COLORS = 10
colors = []

filename = input("Enter the name of the color file (primary.dat or secondary.dat): ")
infile = open(filename, 'r')

while len(colors) < MAX_COLORS:
    line = infile.readline()
    if not line:
        break
    colors.append(line.rstrip())

infile.close()

print('The colors are:')
for color in colors:
    print('  %s' % color)

这样做的问题是,如果您在文件末尾有一个额外的换行符(这很容易意外发生),否则该空行将作为颜色读入。你可能不想要那个。要解决这个问题,你可以这样做:

line = infile.readline().rstrip()
if not line:
    break
colors.append(line)

这将导致您的程序在第一个空白行或文件末尾停止读取,以先到者为准。

【讨论】:

  • 你好,当我去打印“颜色”时,我仍然得到七个空格以及三种颜色,我如何让它只打印其中实际包含数据的内容?
  • 如果你想要,那么不要预先填写列表。只需将我的答案与其他人所说的结合起来(使用colors = [] 然后colors.append(line.rstrip())
  • 效果如何??
  • 您好,little_birdie,感谢您的检查,最后一部分正是我想要让程序正常运行的内容,不幸的是,它是在我的作业截止时间之前添加的,所以我错过了。不过,我真的很感激,人们花这么多时间回答问题只是为了好玩,这真是令人惊讶。我是一名注册会计师的会计师,我需要几个学分才能参加考试,所以我上这门课是为了好玩。它比我想象的要难得多!
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多