本文介绍了计算列表列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,如下所示

I have a list of lists as follows

[
 ['DDX11L1', 'lincRNA', 'chr1', 11869, 14409],
 ['WASH7P', 'lincRNA', 'chr1', 14404, 29570],
 ['MIR1302-2HG', 'lincRNA', 'chr1', 29554, 31109],
 ['FAM138A', 'lincRNA', 'chr1', 34554, 36081],
 ['OR4G4P', 'unprocessed_pseudogene', 'chr2', 52473, 53312],
 ['DDX11L1', 'transcribed_unprocessed_pseudogene', 'chr2', 11869, 14409],
 ['WASH7P', 'lincRNA', 'chr2', 14404, 29570],
 ['MIR1302-2HG', 'lincRNA', 'chr1', 29554, 31109],
 ['FAM138A', 'lincRNA', 'chr3', 34554, 36081],
 ['OR4G4P', 'unprocessed_pseudogene', 'chr2', 52473, 53312]
]

内部列表'chr'会因'chr1''chr2''chrs'而有所不同.取决于那个chr,我想计算出有多少'lincRNA'.(不是所有的'chrs'都会有'lincRNA')

Inside lists 'chr' will get differs as 'chr1', 'chr2' and 'chrs'. Depend on that chr, I want to count how many 'lincRNA' are present.(not all the 'chrs' will have 'lincRNA')

答案示例:

我想要的结果如下:

There are 5 'lincRNA' with 'chr1'
There are 1 'lincRNA' with 'chr2'

预先感谢

推荐答案

您需要分别跟踪每个"chrX"的数量,默认字典会很好地工作:

You need to keep track of the number of each 'chrX' separately, a default dictionary will work nicely:

from collections import defaultdict

count = defaultdict(int)

for ele in lst:
    if ele[1] == 'lincRNA':
        count[ele[2]] += 1

for k, v in count.items():
    print("There are {} 'lincRNA' with '{}'".format(v, k))

结果符合预期:

There are 1 'lincRNA' with 'chr3'
There are 1 'lincRNA' with 'chr2'
There are 5 'lincRNA' with 'chr1'

这篇关于计算列表列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 15:54