【问题标题】:Load a file into an array, and separate it twice with two delimiters将文件加载到数组中,并用两个分隔符将其分隔两次
【发布时间】:2019-04-22 02:18:14
【问题描述】:

我想导入一个文件,然后使用两个分隔符将它们加载到两个数组中。我想打开 data.txt,其中包含:

place1,time1
place2,time2
place3,time3

...

我希望数组 places 成为 ',' 之前的位置,times 成为 ',' 之后的时间

我可以用 open() 成功加载文件,然后用line.strip().split('\n')将它们拆分成一个数组

data = open("data.txt", "r")
infoArray = []
for line in data:
    infoArray.append(line.strip().split('\n'))
data.close()

print infoArray

我希望places[0] 是place1,places[1] 是place2,等等……而time[0] 是time1,time[1],是time2,等等。

【问题讨论】:

    标签: python arrays delimiter


    【解决方案1】:

    您可以使用csv 模块读取逗号分隔的数据,以及在解压可迭代的reader 对象时使用zip()

    >>> import csv
    >>> with open("data.txt") as f:
    ...     reader = csv.reader(f)
    ...     p, t = zip(*reader)
    ... 
    >>> p
    ('place1', 'place2', 'place3')
    >>> t
    ('time1', 'time2', 'time3')
    

    使用csv 而不是尝试自己解析文件的理由是,它将处理诸如引用值(标准CSV 格式)之类的事情,调用str.split(line, ',') 会失败。

    无论您是仅使用file 对象还是csv.reader 结果,其中任何一个都是可迭代的;当您遍历它们时,您将获得文件的各个行。这是一个关于更可见输入的示例,您可以在其中将[1, 2] 可视化为对应于第一行数据,将[3, 4] 可视化为第二行:

    >>> a, b = zip(*[[1, 2], [3, 4]])
    >>> a
    (1, 3)
    >>> b
    (2, 4)
    

    最后,这个例子使用with open(),创建一个上下文管理器和ensures that the file is closed,当你用完之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多