如果您不明白为什么构造不起作用,那么下一个必须阅读您的代码的人也不会。如果你的意思是
b = 1
你应该这么说。在这种情况下,vars() 使您可以访问函数本地字典,因此您的代码相当于
def a():
b = 1
其中b 是a 的本地对象,并在从a 退出时超出范围时消失。
过早的优化是许多人试图猜测 Python 的根源
from itertools import izip
import timeit
import msw.wordlist
def zip_list(p):
"""construct a dictionary of length 100 from a list of strings"""
return dict(zip(p[:100], p[100:]))
def izip_list(p):
"""as zip_list but avoids creating a new list to feed to dict()"""
return dict(izip(p[:100], p[100:]))
def pass_list(p):
"""take 100 elements of a list and do nothing"""
for i in p[:100]:
pass
def exec_pass_list(p):
"""exec() a no-op 100 times"""
for i in xrange(100):
exec('pass')
# returns a list of 64'000 unique lowercase dictionary words for tests
words = msw.wordlist.Wordlist()
words.shuffle()
words = words[:200]
print 'words', words[:5], '...'
for func in ['zip_list', 'izip_list', 'pass_list', 'exec_pass_list']:
t = timeit.Timer('%s(words)' % func,
'from __main__ import words, %s' % func)
print func, t.repeat(number=10**5)
产生:
words ['concatenated', 'predicament', 'shtick', 'imagine', 'stationing'] ...
zip_list [1.8603439331054688, 1.8597819805145264, 1.8571949005126953]
izip_list [1.5500969886779785, 1.5501470565795898, 1.5536530017852783]
pass_list [0.26778006553649902, 0.26837801933288574, 0.26767921447753906]
exec_pass_list [74.459679126739502, 75.221366882324219, 77.538936853408813]
我没有费心去尝试实现 OP 试图做的任何事情,因为不构建字典排序的速度要慢 50 倍,这使得进一步的测试有点愚蠢。