我有一行具有不同的列和一个特定的列(第2列)我想迭代地从另一列(除了0的第12列)添加一些值。我能够为第一个做到这一点,但不能用于其余的列。这是一行
的例子A01 5729384 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
这是所需的输出
A01 5729764 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5730794 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5732051 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
这是我的伪代码
with open('velvet.test.bed') as fh_in:
for line in fh_in:
line = line.strip().split()
x1 = line[11].split(',')
print x1
for j in x1:
print j
if j!= "0":
next
y1 = int(line[1]) + int(j)
test = line[0], " " + str(y1) + " " + " ".join(line[2:])
print test
这是我得到的输出......
A01 5729764 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5730414 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5730641 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
答案 0 :(得分:2)
你去:
>>> a = "A01 5729384 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257"
>>> a = a.split()
>>> add_num = list(map(int,a[-1].split(',')[1:])) #split with whitespace and taken last element, removed 0 and using map to convert them to int
>>> for i in range(len(add_num)):
... print(" ".join([b[0]] + [str(int(b[1])+sum(add_num[:i+1]))] + b[2:]))
...
A01 5729764 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5730794 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
A01 5732051 5730870 Bra1000071 117 - 5729384 5730870 255,0,0 4 281,252,145,229 0,380,1030,1257
您的代码将如下所示:
f = open('file')
for a in f:
a = a.split()
add_num = list(map(int,a[-1].split(',')[1:]))
for i in range(len(add_num)):
print(" ".join([b[0]] + [str(int(b[1])+sum(add_num[:i+1]))] + b[2:]))