gpt4 book ai didi

python - 提高 python 的效率,用于根据嵌套列表中的 ID 循环计数项目

转载 作者:行者123 更新时间:2023-11-28 21:51:57 25 4
gpt4 key购买 nike

我正在尝试提高脚本的效率,该脚本采用表示数据表的嵌套列表,其中包含一列 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 的效率,用于根据嵌套列表中的 ID 循环计数项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29123146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com