python - 提高 python for 循环对嵌套列表中的 ID 进行项目计数的效率

标签 python list for-loop list-comprehension

我正在尝试提高脚本的效率,该脚本采用表示数据表的嵌套列表,其中包含一列 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

最佳答案

使用 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)(线性)算法。

关于python - 提高 python for 循环对嵌套列表中的 ID 进行项目计数的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29123146/

相关文章:

python - 如何在 cythonize 脚本中包含 numpy?

python - 是否有 SVN 命令允许我确认并跳过弹出的窗口(例如确认更新!和将版本提交到文件)?

c - 使用函数更新列表(无返回值)

c - 覆盖链表 C

javascript - 如何将 JavaScript 嵌套 For 循环替换为更清晰、简洁的内容?

java - 使用for循环在静态add方法中获取总和并将其返回给main方法

python - 样式中指定的填充被 Ttk Frame 忽略

python - 根据翻译区分列表

java - 迭代总和

python - 向量和 pandas 列(线性向量)之间的余弦相似度