我正在编写一个欧拉问题,我遇到的问题引起了我的好奇心.我有两个代码片段.一个是列表,另一个是字典.
使用清单:
n=100000
num=[]
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num.append(tmp)
suma+=i
Run Code Online (Sandbox Code Playgroud)
使用词典:
n=100000
num={}
suma=0
for i in range(n,1,-1):
tmp=tuple(set([n for n in factors(i)]))
if len(tmp) != 2: continue
if tmp not in num:
num[tmp]=i
suma+=i
Run Code Online (Sandbox Code Playgroud)
我只关心表现.为什么使用字典的第二个示例运行速度非常快,比第一个带列表的示例快.字典的例子运行速度快了近三十倍!
我使用n = 1000000测试了这两个代码,第一个代码在1032秒内运行,第二个代码在3.3秒内运行,,, amazin'!
我正在编码像这样的东西:
tmp1=tmp[tmp.keys()[0]]
哪里: tmp={'Freud':{3,6,9},'Sigmund':{6}} # a dictionary
这段代码在Python版本中可完美运行。2.7,但如果我在ver中运行相同的版本。3.4我收到TypeError:无法散列的类型:'dict_keys'为什么会出现?我该如何修复它。3.4?