簡體   English   中英

這兩種列表遍歷方法之間是否存在時間復雜度差異?

[英]Is there a time complexity difference between these two methods of list traversal?

時間復雜度有差異嗎? 或者他們是一樣的嗎? 我很難說(python 3.5)

list_of_dict = [{'name':'alan', 'age':5}, {'name':'alice', 'age':6}]

# first method
names = []
ages  = []
for i in range(len(list_of_dict)):
    names.append(list_of_dict[i]['name'])
    ages.append(list_of_dict[i]['age'])

# second method

names = [x['name'] for x in list_of_dict]
ages  = [x['age'] for x in list_of_dict]

我提前為這個問題的潛在微不足道的事情道歉。 我是一名學生,在繼續學習的過程中,我非常感激您的見解。

就漸近時間復雜度而言,它們是相同的。

這兩種方法都需要對列表中的每個元素進行常量字典訪問(平均為常量時間),因此兩者都為O(n)

如果你關心常數,那將很難說,並且可能在不同的解釋器之間有所不同,這可能會優化不同的東西。

除了理論上的復雜性之外,如果你想要或者使用ipython使用%timeit ,你可以計時

第一種方法: 10 loops, best of 3: 58.2 ms per loop

第二種方法: 10 loops, best of 3: 56.3 ms per loop

它們非常接近,需要使用更大的數據集進行檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM