Python 多行在一列中共享一个值,如何将所有这些行放在一行中?
我正在处理一个文本文件,它看起来像这样: rs001 EEE /n rs008 EEE /n rs345 EEE /n rs542 CHG /n re432 CHG /n rs001 EEE/n rs008 EEE/n rs345 EEE/n rs542 CHG/n re432 CHG/n 我希望能够将第2列中共享相同值的所有行折叠为一行(例如,Python 多行在一列中共享一个值,如何将所有这些行放在一行中?,python,unix,text,row,Python,Unix,Text,Row,我正在处理一个文本文件,它看起来像这样: rs001 EEE /n rs008 EEE /n rs345 EEE /n rs542 CHG /n re432 CHG /n rs001 EEE/n rs008 EEE/n rs345 EEE/n rs542 CHG/n re432 CHG/n 我希望能够将第2列中共享相同值的所有行折叠为一行(例如,rs001 rs008 rs345 EEE)。有没有一种简单的方法可以使用unix文本处理或python实现这一点 谢谢一个选项是建立一个以第
rs001 rs008 rs345 EEE
)。有没有一种简单的方法可以使用unix文本处理或python实现这一点
谢谢一个选项是建立一个以第2列数据为基础的字典:
#!/usr/bin/env python
from __future__ import with_statement
from itertools import groupby
with open('file','r') as f:
# We define "it" to be an iterator, for each line
# it yields pairs like ('rs001','EEE')
it=(line.strip().split() for line in f)
# groupby does the heave work.
# lambda p: p[1] is the keyfunction. It groups pairs according to the
# second element, e.g. 'EEE'
for key,group in groupby(it,lambda p: p[1]):
# group might be something like [('rs001','EEE'),('rs008','EEE'),...]
# key would be something like 'EEE', the value that we're grouping by.
print('%s %s'%(' '.join([p[0] for p in group]),key))
from collections import defaultdict #defaultdict will save a line or two of code
d = defaultdict(list) # goal is for d to look like {'EEE':['rs001', 'rs008', ...
for line in file('data.txt', 'r'):
v, k = line.strip().split()
d[k].append(v)
for k, v in d.iteritems(): # print d as the strings you want
print ' '.join(v+[k])
这种方法的优点是,它不需要将第2列的术语分组在一起(尽管问题中没有直接指定第2列是否预先分组)。这里为您提供一个惊喜
$ awk '{a[$2]=a[$2]FS$1}END{for(i in a)print i,a[i]}' file
EEE rs001 rs008 rs345
CHG rs542 re432