如何在变量中存储列值

2024-05-15 22:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理包含多个列的制表符分隔的文件。每列包含3000多条记录。在

Column1     Column2  Column3     Column4
1000041     11657    GenNorm     albumin
1000043     24249    GenNorm     CaBP
1000043     29177    GenNorm     calcium-binding protein
1000045     2006     GenNorm     tropoelastin

问题:使用Python时,如何读取制表符分隔的文件并将每列(及其记录)存储在单个变量中。使用“打印”打印出特定列

初步代码:到目前为止,我使用此代码来读取tsv文件

^{pr2}$

Tags: 文件代码记录制表符bindingcolumn1proteincolumn2
2条回答

不确定python中的代码,但是使用这个循环。一旦你把所有的东西都存储到字典中,然后使用这个循环,然后使用函数调用索引来打印方法,你可以修改函数以适合你想要的键,你可以通过一个词来搜索等等

int mainCounter = 0;
int counter1 = 0;
string arrColumn1[3000];

int counter2 = 0;
string arrColumn1[3000];

int counter3 = 0;
string arrColumn1[3000];

int counter4 = 0;
string arrColumn1[3000];

for(int i = 0; i<dictionary.length; ++i){
      switch ( mainCounterounter )
      {
         case 0:
            arrColumn1[counter1] = dictionary[i];
            ++counter1;
            ++mainCounter;
            break;
         case 1:
            arrColumn2[counter2] = dictionary[i];
            ++counter2;
            ++mainCounter;
            break;
         case 2:
            arrColumn3[counter3] = dictionary[i];
            ++counter3;
            ++mainCounter;
            break;
         case 3:
            arrColumn4[counter4] = dictionary[i];
            ++counter4;
            mainCounter = 0;
            break;
      }
}

^{2}$

抱歉,这是所有相当难的代码,但我希望它能给你一些想法,你可以调整它

我想你只是在问如何将一个CSV文件从一个行序列“转置”到一个列序列。在

在Python中,可以通过使用zip函数来转换iterable的任何iterable:

with open("sample1.txt") as samplefile:
    reader = csv.reader(samplefile, delimiter="\t")
    columns = zip(*reader)

现在,如果要按顺序打印每个列:

^{2}$

这里,columns是元组的迭代器。如果需要其他格式,例如将列名映射到值列表的dict,则可以轻松地对其进行转换。例如:

columns = {column[0]: list(column[1:]) for column in columns}

或者,如果要将它们放在四个独立的变量中,只需使用普通元组解包:

col1, col2, col3, col4 = columns

但似乎没有很好的理由这么做。在

相关问题 更多 >