我基本上在下面的Start()
方法中定义了一组参数。除了request.Continuation
可以具有6
或3
的值以外,大多数参数都相同。我的想法是要列出一个将得到值6的符号列表(在self.continuation
中),并说诸如“如果在self.continuation中,值为= 6,否则为3”。
我对python来说还很陌生,所以这可能还很遥远,但是我不确定这是否是lambda
表达式的好用例。
class BarsRequestSample(CELEnvironment.CELSinkBase):
def __init__(self):
self.symbols = ['CLES12Z', 'HOE']
self.continuation=['ClES12Z', 'CLES6M']
def Start(self):
for symbol in self.symbols:
request.Symbol = symbol
request.RangeStart = 0
request.RangeEnd = -60
request.IntradayPeriod = 5
request.Continuation = 6
request.UpdatesEnabled = True
request.EqualizeCloses = True
request.SessionsFilter = 31
我知道我能做的事
def Start(self):
for symbol in self.symbols:
request.Symbol = symbol
request.RangeStart = 0
request.RangeEnd = -60
request.IntradayPeriod = 5
#potential attempt
if symbol in self.continuation:
request.Continuation = 6
else:
request.Continuation = 3
request.UpdatesEnabled = True
request.EqualizeCloses = True
request.SessionsFilter = 31
我只是直觉,可能会有更简洁的方法来做同样的事情-感激任何想法!
答案 0 :(得分:2)
我将符号列表设为一组。集包含是O(1)操作,而列表是O(n)。对于两个元素来说都没有关系,但这是一个很好的习惯。
self.continuation = {'ClES12Z', 'CLES6M'}
您可以使用conditional expression将分配压缩为一行:
request.Continuation = 6 if symbol in self.continuation else 3
答案 1 :(得分:-2)
对于lambda:
https://github.com/baruchel/continuation/blob/master/continuation/init.py
"""
A module for adding a call/cc feature to Python.
"""
__version__ = '0.1'
__internal_type_error__ = (
"Argument of a continuation must be a continuable function."
)
class _Continuation(Exception):
def __init__(self, f, args, kwargs):
self.func, self.args, self.kwargs = f, args, kwargs
class Continuation():
def __init__(self, calling_id):
self.calling_id = calling_id
def __callback__(self, f):
if isinstance(f, _Continuation):
f.uid = id(self)
raise f
raise TypeError(__internal_type_error__)
def __call__(self, f):
return lambda *args, **kwargs: self.__callback__(f(*args, **kwargs))
__lshift__ = __call__
def with_continuation(func):
def _w(*args, **kwargs):
return _Continuation(func, args, kwargs)
_w.__with_continuation_signature__ = True
return _w
class _with_CC():
def __call__(self, f):
try:
_ = f.__with_continuation_signature__
except AttributeError:
raise TypeError(__internal_type_error__)
return (
lambda *args, **kwargs:
_with_CC().__callback__(f(*args, **kwargs)))
__rshift__ = __call__
def __callback__(self, f):
k = Continuation(id(self))
i = id(k)
while True:
try:
return (f.func)(k)(*f.args, **f.kwargs)
except _Continuation as e:
if i == e.uid: f = e
else: raise e
with_CC = _with_CC()