【问题标题】:How to store split into an array如何将拆分存储到数组中
【发布时间】:2022-10-13 23:52:28
【问题描述】:

我想将拆分的值存储在一个数组中。我尝试在 for 循环之外打印它,但它只给了我一个值。

Date            Close/Last     Volume        Open          High           Low
10/06/2021      $142           83221120      $139.47       $142.15        $138.37
def stocks(file) :
    try:
        fh = open(file, 'r')
    except IOError:
        print("error opening file ....", file)
    else:
        arr = {}
        records = fh.readlines()
        for record in records:
            fields = record.split(',')
            arr = fields[2]
        print(arr)
        fh.close()

【问题讨论】:

  • 你能添加一个输入文件的例子吗?
  • arrdictarr = fields[2] 应该做什么?你的意思是arr[fields[2]] = fields? (另外,你可能想看看csv 模块。)
  • 您需要使用list.append() 方法将其附加到数组中。
  • 此代码中没有数组。现在您已经编辑了问题以显示示例数据,我建议您参考CSV模块,因为这就是您的数据的样子
  • @PaulinaKhew 我为输入文件添加了一个示例。索引应该是 Volume,我正在尝试存储它的值

标签: python arrays


【解决方案1】:

split 函数正在做你期望它做的事情。但是,在for 循环中,您将创建这个新变量arr,并将其分配给fields[2]。我假设你想附加这个值到数组。还,

arr = {}

初始化字典而不是数组。通过这些更改,您的代码如下:

def stocks(file) :
    try:
        fh = open(file, 'r')
    except IOError:
        print("error opening file ....", file)
    else:
        arr = []
        records = fh.readlines()
        for record in records:
            fields = record.split(',')
            arr.append(fields[2])
        print(arr)
        fh.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多