小编fro*_*ard的帖子

Python字典vs列表,哪个更快?

我正在编写一个欧拉问题,我遇到的问题引起了我的好奇心.我有两个代码片段.一个是列表,另一个是字典.

使用清单:

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'!

python performance dictionary list

11
推荐指数
3
解决办法
2万
查看次数

不可散列的类型:'dict_keys'-可正常运行。2.7.5但不在3.4中

我正在编码像这样的东西: 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?

python typeerror

0
推荐指数
1
解决办法
6992
查看次数

标签 统计

python ×2

dictionary ×1

list ×1

performance ×1

typeerror ×1