Python 字典的遍歷

2021-09-02 06:17:28 字數 2496 閱讀 8579

# encoding: utf-8

test_dict =

# 不同的遍歷方法

def test1():

for key in test_dict: # 這種最快, 其實也很顯而易見

pass

def test2():

for key in test_dict.keys():

pass

def test3():

for key, value in test_dict.items():

pass

if __name__ == '__main__':

from timeit import timer

t1 = timer("test1()", "from __main__ import test1")

t2 = timer("test2()", "from __main__ import test2")

t3 = timer("test3()", "from __main__ import test3")

# 執行100,000次的時間

print t1.timeit(100000)

print t2.timeit(100000)

print t3.timeit(100000)

# 3次執行100,000次的時間

print t1.repeat(3, 100000)

print t2.repeat(3, 100000)

print t3.repeat(3, 100000)

結果:

0.0656280517578

0.0932841300964

0.217456817627

[0.06363296508789062, 0.062133073806762695, 0.0649728775024414]

[0.08316302299499512, 0.08275103569030762, 0.08605194091796875]

[0.21467804908752441, 0.19786405563354492, 0.20139288902282715]

但空的迴圈沒有意義

# encoding: utf-8

test_dict =

# 不同的遍歷方法

def test1():

data = {}

for key in test_dict:

data[key] = test_dict[key]

return data

def test2():

data = {}

for key in test_dict.keys():

data[key] = test_dict[key]

return data

def test3():

data = {}

for key, value in test_dict.items():

data[key] = value

return data

print test1()

print test2()

print test3()

if __name__ == '__main__':

from timeit import timer

t1 = timer("test1()", "from __main__ import test1")

t2 = timer("test2()", "from __main__ import test2")

t3 = timer("test3()", "from __main__ import test3")

# 執行100,000次的時間

print t1.timeit(100000)

print t2.timeit(100000)

print t3.timeit(100000)

# 3次執行100,000次的時間

print t1.repeat(3, 100000)

print t2.repeat(3, 100000)

print t3.repeat(3, 100000)

結果:0.39611697197

0.423596143723

0.477458953857

[0.41298508644104004, 0.3765869140625, 0.3731379508972168]

[0.4185318946838379, 0.42104601860046387, 0.4249718189239502]

[0.42894506454467773, 0.4049968719482422, 0.3907771110534668]

差別沒那麼明顯, 不同的遍歷在不同地方處理資料

python遍歷字典

user 0 定義乙個列表 print user 0.items 方法items,返回乙個鍵 值對列表 for key,value in user 0.items for迴圈依次將每個鍵 值對分別儲存在key,value這兩個變數中 print key.title print value.title...

遍歷字典 遍歷字典

寫在前面 你必須先成為什麼,然後才能遇到什麼。找不到真正的自我,人生也許會成功,但絕不會精彩。遍歷所有的鍵 值對 items 使用for迴圈遍歷字典,宣告兩個變數用於儲存鍵對值中的鍵和值,使用items 方法返回字典中的乙個鍵 對值列表,並且將鍵對值依次儲存到指定的變數中 注意 在遍歷字典時,鍵對值...

Python遍歷字典中的鍵

遍歷字典中的鍵 對於餐館中的廚師來說,他們並不想要知道菜的 只需要知道菜名然後將其做出來就行。所以對於廚師來說,我們需要遍歷menu字典中的所有菜名。python為字典型別內建了keys 方法,該方法會將字典裡的鍵遍歷出來,例如 建立並初始化menu選單字典 menu 利用keys 方法遍歷輸出鍵 ...