offsetting iterator
I've got this :
d = {"date": tuple(date),"open":tuple(open),"close":tuple(close)}
comp1 = zip(d['open'],d['close'])
for i in comp1:
if i[0]<i[1]:
print "bar up"
if i[0]>i[1]:
print "bar down"
It's all 开发者_开发问答well and good, it tells me if a bar is up or down, now I would like to "shift" my iteration (by one for example), but I don't know the syntax to it . The logic would be :
"if PREVIOUS bar is UP THEN print "yes" if CURRENT bar is also UP " .
Does it make sense ?
cheers,
If you're using a zip iterator why not just take it to the next level?
comp1 = zip(d['open'],d['close'],d['open'][1:],d['close'][1:])
and there you have it as long as the tuples have length greater than 1. Now you can iterate over not only the tuples but also the next element of each tuple too.
up = lambda a, b: a < b
for prev, b in zip(comp1, comp1[1:]):
if up(*prev) and up(*b):
print "yes"
Explanation
up = lambda a, b: a < b
creates function of two arguments. It is equivalent tooperator.lt
.for prev, b in zip(comp1, comp1[1:]):
uses sequence unpacking (the same as in:x, y = "xy"
), zip() function, list slicing.if up(*prev) and up(*b):
uses the*expression
syntax for function calls.
You will likely need to have a simple bit of logic to your loop, that implements what you need. See the following for just a rough idea
PreviousWasUp = False
for i in comp1:
...
if i[0] > i[1]:
if PreviousWasUp:
print "bar up"
PreviousWasUp = True
else:
PreviousWasUp = False
You could turn the iteration you currently do into list comprehension, and then iterate on the list obtained:
bars = [i[0]<i[1] for i in comp1]
for b in range(1,len(bars)):
if bars[b] and bars[b-1]:
print "yes"
精彩评论