1

我想加入文件中的两行,取决于它们是否以相同的元素开头。
我可以将每一行的第一个元素变成一个列表,并使用这个列表中的元素来搜索每一行,但这似乎不是最有效的方法?

我有以下文件

1,AF534061.1,T,A  
1,K02718.1,T,A  
16,AF534061.1,G,-  
16,K02718.1,G,-  
17,AF534061.1,T,-  
17,K02718.1,T,-  
18,AF534061.1,A,-  
18,K02718.1,A,-  
19,AF534061.1,T,-  
19,K02718.1,T,-  
20,AF534061.1,A,-  
20,K02718.1,A,-  
21,AF534061.1,A,-   
21,K02718.1,A,-  
24,AF534061.1,C,T   

如果第一项在行之间共享,我想加入行。所以我想得到以下输出

1,AF534061.1,T,A,1,K02718.1,T,A
16,AF534061.1,G,-,16,K02718.1,G,-
17,AF534061.1,T,-,17,K02718.1,T,-
18,AF534061.1,A,-,18,K02718.1,A,-
19,AF534061.1,T,-,19,K02718.1,T,-
20,AF534061.1,A,-,20,K02718.1,A,-
21,AF534061.1,A,-,21,K02718.1,A,-
24,AF534061.1,C,T

在这个例子中,看起来我可以加入每隔一行,但我希望(需要)使代码更通用!

我不认为这很难,但我似乎无法弄清楚!谢谢您的帮助

4

3 回答 3

6

Python 标准库充满了工具。对于这项工作,请使用itertools.groupby

import itertools

lines = '''1,AF534061.1,T,A
1,K02718.1,T,A
16,AF534061.1,G,-
16,K02718.1,G,-
17,AF534061.1,T,-
17,K02718.1,T,-
18,AF534061.1,A,-
18,K02718.1,A,-
19,AF534061.1,T,-
19,K02718.1,T,-
20,AF534061.1,A,-
20,K02718.1,A,-
21,AF534061.1,A,-
21,K02718.1,A,-
24,AF534061.1,C,T'''.split('\n')

for key, group in itertools.groupby(lines, lambda line: line.partition(',')[0]):
    print ','.join(group)
于 2012-07-14T02:14:43.623 回答
1

您可以使用正则表达式和反向引用。

print re.sub(r'(([^,]+).*)\n(\2.*\n)', r'\1\3', data)

这是解释的表达式:

(             # Start of first line
 (            # Start of first part of line, refered to as \2
  [^,]+       # Everything before the first comma
 )
 .*           # Remainder of first line
)             # This new line isn't in any capture groups, so it'll be 
\n            #  removed from any matched results
(             # Start of second line
  \2          # This takes the first part of the first line and requires 
              #  it to match again
  .*          # Remainder of second line
  \n          # We include this newline to make the next search start at 
              #  the start of the following line.  It's reinserted because
              #  it's in the second line's capture group.
)
于 2012-07-14T02:09:43.020 回答
-2

我没有测试过这段代码,但这样的东西应该可以工作:

 common = {}
 for line in file.readLines():
   prefix = line.split(",")[0]
   if prefix in common:
     common[prefix].append(line)
   else:
     common[prefix] = [line]

 for key, values in common:
   print values.join(",")
于 2012-07-14T02:13:21.470 回答