我有一行具有不同的列,对于一个特定的列(第2列),我想迭代地添加来自另一列(第12列,除0外)的一些值。我能够在第一个栏目中做到这一点,但在其余的栏目中却无法做到。这是该行的示例

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

最佳答案

干得好:

>>> 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:]))

关于python - 如何在python中迭代地向列添加特定值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27164265/

10-16 17:12