提高python对嵌套列表中的ID进行项计数的Python效率 - python

我正在尝试提高一个脚本的效率,该脚本采用一个嵌套列表来表示数据表,该嵌套列表带有一列ID(每个ID可能有许多条目)。该脚本计算具有100多个条目和200多个条目的ID的数量。

有没有一种方法可以不必每次都借助列表理解来遍历列表?

list_of_IDs = [row[4] for row in massive_nested_list] ### get list of ID numbers
list_of_IDs = set(list_of_IDs) ### remove duplicates
list_of_IDs = list(list_of_IDs)
counter200 = 0
counter100 = 0
for my_ID in list_of_IDs:
    temp = [row for row in massive_nested_list if row[4] == my_ID]
    if len(temp) > 200:
        counter200 += 1
    if len(temp) > 100:
        counter100 += 1

python大神给出的解决方案

使用collections.Counter() instance来计算您的ID。无需先收集所有可能的ID。然后,您可以从此处整理计数:

from collections import Counter

counts = Counter(row[4] for row in massive_nested_list)
counter100 = counter200 = 0
for id, count in counts.most_common():
    if count >= 200:
        counter200 += 1
    elif count >= 100:
        counter100 += 1
    else:
        break

给定N个嵌套列表中的K个唯一ID,您的代码将采用O(KN)循环来计算所有内容;最坏的情况(K == N),这意味着您的解决方案要花费二次时间(每增加一行,您需要做N倍的工作)。上面的代码减少了N个项目上的一个循环,然后减少了K个项目上的另一个循环,使其成为O(N)(线性)算法。