我想创建一个装饰方法来分配函数将使用但不会自行传递的变量。
例如在 lambda r 中添加新变量 y,我以这种方式编写了代码但没有工作。
r = lambda x:x+y
def foo(func):
def wrapped(*args,**kwargs):
y = 3
return func(y=y,*args,**kwargs)
return wrapped
r = foo(r)
print(r(444))
Run Code Online (Sandbox Code Playgroud)
这也行不通
r = lambda x:x+y
def foo(func):
def wrapped(*args,**kwargs):
y = 3
return func(*args,**kwargs)
return wrapped
r = foo(r)
print(r(444))
Run Code Online (Sandbox Code Playgroud) 例如我有一个清单
L = [1,33,55,777,'abc'....]
Run Code Online (Sandbox Code Playgroud)
我想从某个点迭代它,比如第二个元素,这就是我以前做的事情
for x in L[1:]:
print(x)
Run Code Online (Sandbox Code Playgroud)
因此可以工作,但是制作原始列表的一部分的浅表副本,或者我可以使用下标
for x in range(1,len(L)):
print(l[x])
Run Code Online (Sandbox Code Playgroud)
有没有办法在python中创建一个降低成本的迭代器?这可能看起来像这样:
for x in iter(L,1): #iter from index 1 to the end
print(L[x])
Run Code Online (Sandbox Code Playgroud) 使用2维数组,看起来像这样:
myarray = [['jacob','mary'],['jack','white'],['fantasy','clothes'],['heat','abc'],['edf','fgc']]
Run Code Online (Sandbox Code Playgroud)
每个元素都是一个具有固定长度元素的数组.如何成为这个,
mylist = ['jacob','mary','jack','white','fantasy','clothes','heat','abc','edf','fgc']
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案
mylist = []
for x in myarray:
mylist.extend(x)
Run Code Online (Sandbox Code Playgroud)
我猜应该更简单
为什么我问这个问题,因为我总是担心这种风格的代码
def callsomething(x):
if x in (3,4,5,6):
#do something
Run Code Online (Sandbox Code Playgroud)
如果函数调用的东西经常被调用,那么(3,4,5,6)是否浪费了太多的空间和时间?在某些语言如C中,它可能被推入数据段,如常量,但在python中,我不知道它是如何工作的,所以我倾向于编写这样的代码
checktypes = (3,4,5,6)#cache it
def callsomething(x):
global checktypes
if x in checktypes:
#do something
Run Code Online (Sandbox Code Playgroud)
但经过测试我发现这种方式使程序变慢,在更复杂的情况下,代码将是这样的:
types = (3,4,5,6)
def callsomething(x):
global types
for t in types:
t += x
#do something
Run Code Online (Sandbox Code Playgroud)
仍然比这慢
def callsomething(x):
for t in (3+x,4+x,5+x,6+x):
#do something
Run Code Online (Sandbox Code Playgroud)
在这种情况下,程序必须创建(3 + x,4 + x,5 + x,6 + x),对吧?但它仍然比第一个版本更快,但不是太多了.
我知道python中的全局var访问会减慢程序,但它与创建结构的比较有多大?
我用它来设置我的日志,但没有用。
tornado.options.options['log_file_prefix'].set('/opt/logs/my_app.log')
tornado.options.parse_command_line()
Run Code Online (Sandbox Code Playgroud)
得到这个错误
tornado.options.options['log_file_prefix'].set('/logs/my_app.log')
TypeError: 'OptionParser' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)
我希望将日志打印在终端和日志文件上,并且我通过 xml 配置文件而不是直接通过命令行启动我的应用程序,我该怎么做?