【问题标题】:Storing integers from text file to an array将整数从文本文件存储到数组
【发布时间】:2019-04-13 16:38:43
【问题描述】:

我的任务是将文本文件中的整数分配给 python 中的数组。

我尝试逐行阅读和拆分,但没有奏效。

任务是这样的:我们有一个数组

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

0 0 0 0 0 0 0 0 4 0 0 0 0 0

0 0 0 0 0 0 0 0 0 3 0 0 0 0

0 0 0 0 0 0 0 5 0 0 6 0 0 0

0 0 0 0 0 0 0 0 0 0 1 0 0 0

0 0 0 0 0 0 0 0 0 0 0 2 9 0

0 0 0 0 0 0 0 0 0 0 10 0 0 0

0 0 0 0 0 0 0 0 0 0 0 0 0 11

0 0 0 0 0 0 0 0 0 0 0 0 0 1

0 0 0 0 0 0 0 0 0 0 0 0 0 8

0 0 0 0 0 0 0 0 0 0 0 0 0 9

0 0 0 0 0 0 0 0 0 0 0 0 0 14

0 0 0 0 0 0 0 0 0 0 0 0 0 5

0 0 0 0 0 0 0 0 0 0 0 0 0 0

这需要分配给一个数组 x 以便在其他函数中使用它。

【问题讨论】:

  • 嗨,欢迎来到 StackOverflow。请熟悉How to Askhelp center。请注意,“我尝试逐行阅读和拆分,但没有奏效。”不是一个足够清晰的问题描述。向我们展示您尝试了什么以及如何失败
  • 文件中有多余的换行符吗?

标签: python arrays python-3.x file-io


【解决方案1】:

执行以下操作:

with open('my_raw_file.txt', 'r') as file:
    all_file = file.read().strip()  # Read and remove any extra new line
    all_file_list = all_file.split('\n')  # make a list of lines
    final_data = [[int(each_int) for each_int in line.split()] for line in all_file_list]  # make list of list and convert to int 
    print(final_data)

【讨论】:

    【解决方案2】:

    如果您不介意 numpy 数组和 pandas:

    import pandas as pd
    integers = pd.read_csv('test.txt', sep=" ", header=None)
    

    【讨论】:

    • 它不认识pandas,去google一下,谢谢!
    • 可以通过pip install pandas安装。另外,我刚刚修复了导入语句
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多