简体   繁体   English

将矩阵导出到python中的文本文件

[英]exporting a matrix to a text file in python

I have a list of lists(matrix) in python and I want to export it to a text file. 我在python中有一个lists(matrix)列表,我想将其导出到文本文件。 the inner lists have 3 elements. 内部列表包含3个元素。 my file would have 3 columns. 我的文件将有3列。 in other word, the first column would have the first element of inner list, the 2nd column would have the 2nd element of inner lists and the 3rd column would have the 3rd elements. 换句话说,第一列将具有内部列表的第一元素,第二列将具有内部列表的第二元素,第三列将具有第三元素。 I tried to make it but all elements would be in a single column. 我试图做到这一点,但所有元素都在同一列中。 here is a small example: input: 这是一个小例子:输入:

[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]]

output(which would be a text file): 输出(将是一个文本文件):

ENSG00000137288.5  0.16721311  0.13442624
ENSG00000116032.5  0.094311371  0.1444611
ENSG00000167578.12  0.062894806  0.10162043

do you guys know how to do that? 你们知道怎么做吗? thanks 谢谢

The easiest way without using numpy, pandas or any other external package would be something like this: 不使用numpy,pandas或任何其他外部软件包的最简单方法是:

data = [
    ['ENSG00000137288.5', 0.16721311, 0.13442624],
    ['ENSG00000116032.5', 0.094311371, 0.1444611],
    ['ENSG00000167578.12', 0.062894806, 0.10162043]
]

# builtin python functions
data_file = "\n".join([" ".join(map(lambda x: str(x),row)) for row in data])
print data_file

Try the csv.writer : 试试csv.writer

import csv
your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]]
with open('output.txt', 'wb') as csvfile:
    w = csv.writer(csvfile, delimiter=' ')
    for row in your_data:
        w.writerow(row)

You can specify any delimiter you want (comma,tab,space etc.) and there can be any number of columns and rows in the matrix. 您可以指定所需的任何定界符(逗号,制表符,空格等),并且矩阵中可以有任意数量的列和行。

If you want to open the file in excel, then use comma , as delimeter and change file name to .csv : 如果你想在Excel中打开该文件,然后用逗号,作为分隔符和更改文件名.csv

import csv
your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]]
with open('output.csv', 'wb') as csvfile:
    w = csv.writer(csvfile, delimiter=',')
    for row in your_data:
        w.writerow(row)

or using tab with dialect='excel' : 或使用带有dialect='excel' tab

import csv
your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]]
with open('output.xls', 'wb') as csvfile:
    w = csv.writer(csvfile, delimiter='\t', dialect='excel')
    for row in your_data:
        w.writerow(row)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM