在单独的值中分割字典中的值

时间:2015-03-13 21:47:24

标签: python

我有这种类型的字符串:

sheet = """
magenta
turquoise,PF00575
tan,PF00154,PF06745,PF08423,PF13481,PF14520
turquoise, PF00011
NULL
"""

每一行都以标识符开头(例如tan,magenta ......)我想要的是计算每个标识符的每个PF编号的出现次数。

所以,最终的结构将是这样的:

         magenta  turquoise tan NULL
PF00575   0          0       0   0
PF00154   0          1       0   0
PF06745   0          0       1   0
PF08423   0          0       1   0
PF13481   0          0       1   0
PF14520   0          0       1   0
PF00011   0          1       0   0

我开始创建一个字典,其中一行中的每个第一个单词都是一个键,然后我想要它后面的PF数字作为值。

当我使用此代码时,我将值作为字符串列表而不是字典中的单独值获取:

lines = []
lines.append(sheet.split("\n"))
flattened=[]
flattened = [val for sublist in lines for val in sublist]
pfams = []
for i in flattened:
    pfams.append(i.split(","))
d = defaultdict(list)
for i in pfams:
pfam = i[0]
d[pfam].append(i[1:])

所以,结果如下:

defaultdict(<type 'list'>, {'': [[], []], 'magenta': [[]], 'NULL': [[]], 'turquoise': [['PF00575']], 'tan': [['PF00154', 'PF06745', 'PF08423', 'PF13481', 'PF14520']]})

如何拆分PF编号,使它们在字典中是单独的值,然后计算每个键的每个唯一PF编号的出现次数?

2 个答案:

答案 0 :(得分:1)

使用collections.Counterhttps://docs.python.org/2/library/collections.html#collections.Counter

import collections

sheet = """
magenta
turquoise,PF00575
tan,PF00154,PF06745,PF08423,PF13481,PF14520
NULL
"""

acc = {}
for line in sheet.split('\n'):
    if line == "NULL":
         continue
    parts = line.split(',')
    acc[parts[0]] = collections.Counter(parts[1])

编辑:现在累积每个键的所有PF值

acc = collections.defaultdict(list)
for line in sheet.split('\n'):
    if line == "NULL":
         continue
    parts = line.split(',')
    acc[parts[0]] += parts[1:]
acc = {k: collections.Counter(v) for k,v in acc.iteritems()}

最终修改计算每个PF值的颜色出现次数,这也是我们最终的结果:

acc = collections.defaultdict(list)
for line in sheet.split('\n'):
    if line == "NULL":
         continue
    parts = line.split(',')
    for pfval in parts[1:]
         acc[ pfval ] += [ parts[0] ]
acc = {k: collections.Counter(v) for k,v in acc.iteritems()}

答案 1 :(得分:0)

感谢devwhed的dwblas,这是我找到解决这个任务的最有效方式:

我建立了一个字典,其关键字是PFnumber,以及按照我希望打印颜色的方式排列的列表。

colors_list= ['cyan','darkorange','greenyellow','yellow','magenta','blue','green','midnightblue','brown','darkred','lightcyan','lightgreen','darkgreen','royalblue','orange','purple','tan','grey60','darkturquoise','red','lightyellow','darkgrey','turquoise','salmon','black','pink','grey','null']
lines = sheet.splitlines()
counts = {}

for line in lines:
    parts = line.split(",")
    if len(parts) > 1:
        ## doesn't break out the same item in the list many times
        color=parts[0].strip().lower()
        for key in parts[1:]:  ## skip color
            key=key.strip()
            if key not in counts:
                ## new key and list of zeroes-print it if you want to verify
                counts[key]=[0 for ctr in range(len(colors_list))]

            ## offset number/location of this color in list
            el_number=colors_list.index(color)
            if color > -1:  ## color found
                counts[key][el_number] += 1
            else:
                print "some error message"

import csv

with open("out.csv", "wb") as f:
    writer=csv.writer(f)
    writer.writerow( ["PFAM",] + colors_list)
    for pfam in counts:
    writer.writerow([pfam] + counts[pfam])