python - python中的矩阵文件到字典

标签 python file dictionary matrix

我有一个文件matrix.txt,其中包含:

   A  B  C
A  1  2  3
B  4  5  6
C  7  8  9

我想读取文件的内容并将其存储在字典中,如下所示:

{('A', 'A') : 1, ('A', 'B') : 2, ('A', 'C') : 3,
 ('B', 'A') : 4, ('B', 'B') : 5, ('B', 'C') : 6,
 ('C', 'A') : 7, ('C', 'B') : 8, ('C', 'C') : 9}

最佳答案

以下 Python3 函数将生成所有矩阵项及其索引,与 dict 构造函数兼容:

def read_mx_cells(file, parse_cell = lambda x:x):
  rows = (line.rstrip().split() for line in file)
  header = next(rows)
  for row in rows:
    row_id = row[0]
    for col_id,cell in zip(header, row[1:]):
      yield ((row_id, col_id), parse_cell(cell))

with open('matrix.txt') as f:
  for x in read_mx_cells(f, int):
    print(x)
# ('A','A'),1
# ('A','B'),2
# ('A','C'),3 ...

with open('matrix.txt') as f:
  print(dict(read_mx_cells(f, int)))
# { ('A','A'): 1, ('A','B'): 2, ('A','C'): 3 ... } 
# Note that python dicts dont retain item order

关于python - python中的矩阵文件到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34733479/

相关文章:

java - 计算文件的总计和平均值

c++ - DeleteFile 在最近关闭的文件上失败

python - Python 中的就地快速排序

python - 如何将值分配给列表中的 python 字典

python - scipy curve_fit 在拟合傅里叶函数时不产生平滑的图形

Python:字典和列表

c# - 在一个对象中表示 n 个对象

python - 如何使用 PyKCS11 库验证签名数据

php - 文件创建时间

Python:如何将字典转换为可下标数组?