【问题标题】:Converting file data to nested list将文件数据转换为嵌套列表
【发布时间】:2016-06-28 22:56:40
【问题描述】:

我有一串数字,我想将其转换为嵌套列表。到目前为止,我有

 with open('lifedata.txt') as f:
    table_data = [ line.split() for line in f]
print(table_data)

如果文本文档由这样排列的数字组成,

0000000 0010000 0001000 0111000 0000000 0000000

到目前为止,我的代码只创建了一个嵌套列表,看起来像 [['0000000'], ['0010000'], ['0001000'], ['0111000'], ['0000000'], ['0000000']]

但是,相反,我希望它是 [[0,0,0,0,0,0,0],[],[]] 等等。我也不知道如何将字符串转换为整数。我只是对如何操作原始文本文档来做我想做的事情感到非常困惑。

【问题讨论】:

    标签: python list file python-3.x nested


    【解决方案1】:

    使用这个,它将从txt的每一行返回一个包含数据的列表。

    open('lifedata.txt').readlines()
    

    【讨论】:

      【解决方案2】:

      这是正在发生的事情:

      >>> "0000000".split()
      ['0000000']
      

      相反,对每个字符串中的每个字符调用int()

      [[int(c) for c in line.strip()] for line in f] 
      

      或者,通过map()

      [list(map(int, line.strip())) for line in f]
      

      【讨论】:

      • 如果我尝试调用每个字符,它会给我invalid literal for int() with base 10: '\n'
      • 哇哦,好用!那么 line.strip() 是否需要排除空白空间?
      • @George 在这种情况下,它有助于在末尾去除换行符。
      猜你喜欢
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多