from collections import OrderedDict
from itertools import izip,repeat
import csv
with open("matrix.txt") as f:
r = csv.reader(f, delimiter=" ", skipinitialspace=1)
head = repeat(next(r))
od = OrderedDict((((row[0], k), v) for row in r
for k, v in izip(next(head), row[1:])))
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
pandas
使它非常整洁。你知道吗方法1
方法2
您可以使用
itertools.product
来创建键,使用文件头和转置后的第一列来创建键,然后只需将其余行压缩转换回其原始状态,并创建拆分子字符串的单个iterable。为了维持秩序,我们还需要使用OrderedDict
:输出:
对于python3,只需使用
map
和zip
。你知道吗或者不转置并使用csv库:
输出相同。你知道吗
下面的Python3函数将生成所有带有索引的矩阵项,与
dict
构造函数兼容:相关问题 更多 >
编程相关推荐