特定行中的重新排序列表

时间:2014-12-04 00:04:09

标签: python

我有一个包含这样的行的文件:

r1  1   10
r2  10  1   #second bigger than third (10>1)
r3  5   2   #  ""       ""            (5>2)
r4  10  20

我想重新排列第二个单词大于第三个单词的行,将[3]位置改为[2]位。

期望的输出:

r1  1   10
r2  1   10
r3  2   5
r4  10  20

我已经制作了一个重新排序行的代码,但它只输出重新排序的行,但不是所有行:

with open('test','r') as file, open('reorderedtest','w')as out:

for line in file:
    splitLine = line.split("\t")
    reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ]
    if int(splitLine[1]) > int(splitLine[2]):
        str = "    "
        print str.join(reorderedlist)

它只打印:

r2  1   10
r3  2   5

有任何想法可以获得我想要的输出吗?

2 个答案:

答案 0 :(得分:2)

对现有代码的最简单修改是:

with open('test','r') as file, open('reorderedtest','w')as out:

for line in file:
    splitLine = line.split("\t")
    reorderedlist = [splitLine[0], splitLine[2], splitLine[1] ]
    if int(splitLine[6]) > int(splitLine[7]):
        str = "    "
        print str.join(reorderedlist)
    else:
        print line

答案 1 :(得分:1)

这适用于任意数量的列,第一列中有r#,后面有任意数量的数字列。

with open('test.txt') as fIn, open('out.txt', 'w') as fOut:
    for line in fIn:
        data = line.split()
        first = data[0]    # r value
        values = sorted(map(int, data[1:]))   # sorts based on numeric value
        fOut.write('{} {}\n'.format(first, ' '.join(str(i) for i in values))  # write values back out

生成的out.txt文件

r1 1 10
r2 1 10
r3 2 5
r4 10 20