通过文件和数组同时迭代python for循环

时间:2013-07-02 18:12:57

标签: python arrays file for-loop

我正在尝试遍历文件并在其中添加一个新列,而不是使用两个并发for循环在文件中存在的列。但我不知道如何迭代数组部分。

我有一个数组aa = [1,2,3,4,5] 我的档案是:

I   a   0
II   b   0
III   c   0
IV   d   0
V   f   0

我想要它:

I   a   1
II   b   2
III   c   3
IV   d   4
V   f   5 

我试过python代码:

cmg=[1,2,3,4,5]
fh=open("plink5.map",'r')
fhnew=open("plink5.out",'w+')
for line,i in zip(fh,(0,len(cmg)-1,1)):
    line=line.strip('\n')
    aa=line.split('\t')
    aanew=str(aa[0])+"\t"+str(aa[1])+"\t"+str(cmg[i])
    print(aanew)
   fhnew.write(aanew)
fh.close()
fhnew.close()

我在数组迭代部分中得到错误

1 个答案:

答案 0 :(得分:2)

你要做的是:

for line,i in zip(fh,range((0,len(cmg)  ,1))):
                     ^^^^^            ^^

但更容易的是:

for line,x in zip(fh, cmg):