连接矩阵PYTHON(没有numpy)

时间:2017-11-28 15:45:42

标签: python file matrix

我要手动合并文本文件中包含的两个给定矩阵,而不导入任何类型的模块。它看起来像:

[[1,2][3,4]],[[5,6,7],[8,9,10]]

我有这段代码:

def combine(filename): 
    with open(filename, 'r') as myfile:
        data=myfile.read().split()
        a=data[0].split()
        b=data[1].split()
    a=eval(a[0])
    b=eval(b[0])
    row_a=len(a)
    row_b=len(b)
    col_a=len(a[0])
    col_b=len(b[0])
    concatenated=[]
    if row_a==row_b: #build horizontally 
        for i in range (row_a):
            concatenated.append(a[i])
            for i in range (row_b):
                concatenated.append(b[i])
        return concatenated
    if col_a==col_b: #build vertically
        for i in range (col_a):
            concatenated.append(a[i])
            for i in range (col_b):
                concatenated.append(b[i])
        return concatenated
    else:
        print ("Error")

但它返回:

[[1, 2], [5, 6, 7], [8, 9, 10], [3, 4], [5, 6, 7], [8, 9, 10]]

而不是:

[[1,2,5,6,7],[3,4,8,9,10]]

关于如何使这项工作的任何想法?提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用ast.literal_eval

import ast
final_results = [a+b for a, b in zip(*ast.literal_eval(open('filename.txt')))]

输出:

[[1, 2, 5, 6, 7], [3, 4, 8, 9, 10]]

编辑:没有任何导入,您可以使用eval。但请注意,eval非常不安全,因此只能在受信任来源的字符串上运行:

final_results = [a+b for a, b in zip(*eval(open('filename.txt').read()))]