【问题标题】:How to create an array from an ascii file with python [closed]如何使用python从ascii文件创建数组[关闭]
【发布时间】:2015-01-04 11:44:36
【问题描述】:

我有一个 ascii 文件(example.dat):

3 5 2 1 3 
4 2 3 4 2
2 1 3
2 1 8 7

如何使用 python 创建以下数组:

A = (3, 5, 2, 1, 3, 4, 2, 3, 4, 2, 2, 1, 3, 2, 1, 8, 7)

【问题讨论】:

  • 当您尝试这样做时遇到了什么问题?
  • 那不是数组,是元组。
  • with open('example.dat') as infile: t = tuple(itertools.chain.from_iterable(line.split() for line in infile))

标签: python arrays ascii


【解决方案1】:
input = """3 5 2 1 3 
4 2 3 4 2
2 1 3
2 1 8 7"""

f = [int(i) for i in input.split()]
A = tuple(f)

A 的值现在是:

(3, 5, 2, 1, 3, 4, 2, 3, 4, 2, 2, 1, 3, 2, 1, 8, 7)

重要提示:这不是一个数组,这是一个元组。此外,这仅在您的所有输入都是整数时才有效(因为int(i))。

【讨论】:

    猜你喜欢
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2020-07-02
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2012-03-29
    相关资源
    最近更新 更多