【问题标题】:Trying to Convert a Text file into data structure尝试将文本文件转换为数据结构
【发布时间】:2020-02-16 17:56:20
【问题描述】:

我喜欢这个文本数据作为以下内容。我正在尝试将此文本转换为能够处理的数据结构(Lists of dictionarieslist of lists)。

test.txt

0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0

输出格式如下:

   0     1      1
   ---------------
3| 1    1       1
5| 0    1      0
6| 1    0       0

我尝试了很多东西,但不幸的是没有成功。

【问题讨论】:

  • 你想要什么结构?清单清单?字典列表?列表字典?字典中的字典?
  • 另外,到目前为止,您尝试过什么?您当前的代码有什么问题?
  • 我是初学者,所以我花了很多时间试图了解如何去做,但没有成功
  • 你能发布你的代码和(如果有的话)错误信息吗?另外,对于您有两个名为 1 的列这一事实,您想做什么?
  • 到底是什么问题? Stack Overflow 不是免费的代码编写服务。请参阅:tourHow to Askhelp centermeta.stackoverflow.com/questions/261592/…

标签: python python-3.x numpy multidimensional-array


【解决方案1】:

我不知道这是否正是你想要的结构,但试试这个:

import collections

txt = """0           1           1
3,1         3,1         3,1
5,0         5,1         5,0
6,1         6,0         6,0"""

header = list(map(int,txt.splitlines()[0].split()))

output = collections.OrderedDict()
for line in txt.splitlines()[1:]:
    cols = line.split()
    row_num = int(cols[0].split(",")[0])

    vals = [(header[i],int(c.split(",")[1])) for i, c in enumerate(cols)]
    output[row_num] = vals

print(output)

输出:

OrderedDict([('3', [(0, 1), (1, 1), (1, 1)]), ('5', [(0, 0), (1, 1), (1, 0)]), ('6', [(0, 1), (1, 0), (1, 0)])])

加载文件:

with open("file.txt") as f:
    txt = f.read()

【讨论】:

  • 谢谢,但在我的情况下,它是关于一个 txt 文件而不是一个 txt String
  • 是的,这正是我所需要的
  • 您能否更新您的答案,使其适合file.txt
  • with open('result.info') as infile: header = list(map(int,infile.read().splitlines()[0].split())) output = collections.OrderedDict() for line in infile.read().splitlines()[1:]: print(line) cols = line.split() row_num = cols[0][0] vals = [(header[i],int(c.split(",")[1])) for i, c in enumerate(cols)] output[row_num] = vals print(output)
  • 我在哪里出错了?我越来越空 OrderedDict
猜你喜欢
  • 2016-02-16
  • 1970-01-01
  • 2021-10-30
  • 2016-04-23
  • 2014-07-11
  • 1970-01-01
  • 2015-01-05
  • 1970-01-01
  • 2018-12-01
相关资源
最近更新 更多