简体   繁体   English

从python中的列表创建字典的时间复杂度

[英]Time Complexity to create a dictionary from a list in python

What would be the time complexity to create a dictionary for frequency of occurrence of elements in a list (in python)?为列表中元素的出现频率创建字典(在 python 中)的时间复杂度是多少?

For example: I have a list - ls = [5,3,3,2] I want to create a dictionary to check frequency of each element in the list.例如:我有一个列表 - ls = [5,3,3,2] 我想创建一个字典来检查列表中每个元素的频率。 This is the code for that:这是代码:

freq = {}
for ele in ls:
    if ele in freq:
        freq[ele] += 1
    else:
        freq[ele] = 1

This will create the dictionary from the list, but what would the time complexity be to create the dictionary?这将从列表中创建字典,但是创建字典的时间复杂度是多少?

Any insights on this would be helpful.对此的任何见解都会有所帮助。 Thank you.谢谢你。

It would be linear O(n) complexity as you are only iterating through the list once with no nested loops/recursion/etc... As for checking ele in freq it is O(1) complexity as dicts are hash maps and using dict.__contains__ only does a hash lookup for the value.这将是线性O(n)复杂度,因为您只在没有嵌套循环/递归/等的情况下遍历列表一次...至于检查ele in freq它是O(1)复杂度,因为 dicts 是哈希映射并使用dict.__contains__只对值进行哈希查找。 Although using collections.Counter is the more preferred way:虽然使用collections.Counter是更受欢迎的方式:

from collections import Counter

ls = [5,3,3,2]
freq = Counter(ls)

>>> dict(freq)
{5: 1, 3: 2, 2: 1}

它应该是线性O(n)因为您只是从列表的第一个到最后一个线性循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM