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