我想知道为什么列表理解比附加到列表要快得多.我认为差异只是表达,但事实并非如此.
>>> import timeit
>>> timeit.timeit(stmt='''\
t = []
for i in range(10000):
t.append(i)''', number=10000)
9.467898777974142
>>> timeit.timeit(stmt='t= [i for i in range(10000)]', number=10000)
4.1138417314859
Run Code Online (Sandbox Code Playgroud)
列表理解速度提高了50%.为什么?
我试图找到列表理解的效率,但它看起来比正常的功能操作更昂贵.谁能解释一下?
def squares(values):
lst = []
for x in range(values):
lst.append(x*x)
return lst
def main():
t = timeit.Timer(stmt="lst = [x*x for x in range(10)]")
print t.timeit()
t = timeit.Timer(stmt="squares",setup="from __main__ import squares")
print t.timeit()
lst = [x*x for x in range(10)]
print lst
print squares(10)
----Output:---
2.4147507644
0.0284455255965
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Run Code Online (Sandbox Code Playgroud)
对于相同的输出,与列表理解相比,正常函数在非常短的时间内计算.
我认为列表理解更有效.
是否可以仅使用.get()
字典中的函数来实现此目的?这是我们能做的最好的事情来缩短这段代码吗?
n_dict
是一个Dict
类型(大写D
)并且NES
只是一个列表str
eted_info = {}
for key in n_dict:
if key in NES:
eted_info[key] = n_dict[key]
Run Code Online (Sandbox Code Playgroud)
我只是好奇是否有更好/更 Pythonic 的方式来检索值,就像 C# 那样TryGetValue
。