如何在Python中使用带有列表列表的计数器和zip函数?

时间:2016-10-10 23:37:29

标签: python list error-handling append

我有一份清单清单:

results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]

我创建了一个计数器,用于存储每个列表中每个元素的字符数,只有字符是ATGC [NOT Z]

The desired output is [[4,3],[4,2]]

**

代码:

counters = [Counter(sub_list) for sub_list in results]
    nn =[]
    d = []
    for counter in counters:
            atgc_count = sum((val for key, val in counter.items() if key in "ATGC"))    
            nn.append(atgc_count)
d = [i - 1 for i in nn]
correctionfactor = [float(b) / float(m) for b,m in zip(nn, d)]
print nn
print correctionfactor

"Failed" Output:
[0, 0]
<closed file 'c:/test/zzz.txt', mode 'r' at 0x02B46078>

Desired Output
nn = [[4,3],[4,2]]
correctionfactor = [[1.33, 1.5],[1.33,2]]

**

然后我计算每个字符(pi)的频率,将其平方然后求和(然后我计算het = 1 - sum)。

The desired output [[1,2],[1,2]] #NOTE: This is NOT the real values of expected output. I just need the real values to be in this format. 

** 代码

list_of_hets = []
for idx, element in enumerate(sample):
    count_dict = {}
    square_dict = {}
    for base in list(element):
         if base in count_dict:
            count_dict[base] += 1
        else:
            count_dict[base] = 1
    for allele in count_dict:
        square_freq = (count_dict[allele] / float(nn[idx]))**2
        square_dict[allele] = square_freq        
    pf = 0.0
    for i in square_dict:
        pf += square_dict[i]   # pf --> pi^2 + pj^2...pn^2
    het = 1-pf                    
    list_of_hets.append(het)
print list_of_hets

"Failed" OUTPUT:
[-0.0, -0.0]

** 我需要将list_of_hets中的每个元素乘以校正因子

h = [float(n) * float(p) for n,p in zip(correction factor,list_of_hets)
With the values given above:
h = [[1.33, 1.5],[1.33,2]] #correctionfactor multiplied by list_of_hets 

最后,我需要找到h中每个元素的平均值,并将其存储在新列表中。

The desired output should read as [1.33, 1.75].

我尝试过这个例子(Sum of list of lists; returns sum list)。

hs = [mean(i) for i in zip(*h)]

但是我收到以下错误&#34; TypeError:zip参数#1必须支持迭代&#34;

我知道在第一步修改代码可能会解决问题。我试图手动输入&#34;所需的输出&#34;并运行其余的代码,但没有运气。

2 个答案:

答案 0 :(得分:1)

第一部分可以像这样完成:

BASES = {'A', 'C', 'G', 'T'}

results = [['TTTT', 'CCCZ'], ['ATTA', 'CZZC']]
counts = [[sum(c in BASES for c in s) for s in pair] for pair in results]
>>> counts
[[4, 3], [4, 2]]

获得计数后,还可以使用列表解析来计算修正系数:

correction_factors = [[i/float(i-1) for i in pair] for pair in counts]
>>> correction_factors
[[1.3333333333333333, 1.5], [1.3333333333333333, 2.0]]

但是你需要注意计数为1的情况,因为这会导致除以零错误。我不确定你应该如何处理......值1是否合适?

correction_factors = [[i/float(i-1) if i-1 else 1 for i in pair] for pair in counts]

答案 1 :(得分:0)

首先映射遍历结果。 第二个地图替换'Z'和计数元素。

map(lambda x:map(lambda y:len(y.replace('Z','')),x),l)