且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算列表列表中的元素

更新时间:2022-05-27 22:04:33

您需要分别跟踪每个"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'